【问题标题】:Using jest-fetch-mock and receiving null使用 jest-fetch-mock 并接收 null
【发布时间】:2021-12-28 16:00:48
【问题描述】:

我不确定为什么在尝试“模拟”获取时收到 null。我正在使用 React,沿着 punkapi。我正在使用“jest-fetch-mock”发出模拟请求

fetch.mockResponseOnce(JSON.stringify([{ test: "data" }]))

这是我的虚假回复。我只是不明白为什么我收到空值。 我收到的数据是数组中的一个对象,它正在工作。

这是我的获取请求(工作中):

const random = async () => {
  try {
    const res = await fetch("https://api.punkapi.com/v2/beers/random");
    const newData = await res.json();
    return newData
    } catch (e) {
      return null
    }
  };

export { random }

这是我的测试文件:

import { random } from "./random";
import fetch from 'jest-fetch-mock'
test("collects data", async () => {
  fetch.mockResponseOnce(JSON.stringify([{ test: "data" }]))

  const data = await random()

  expect(data).toEqual([{
    test: "data"
  }])
})

我还通过添加这个来更新我的 setupTest.js。

import fetchMock from 'jest-fetch-mock'

fetchMock.enableMocks()

更新

看起来它从我的 try catch 返回 NULL,但我的测试仍然失败。 Cannot read property 'json' of undefined 是我的错误,它来自我的随机异步函数

【问题讨论】:

    标签: javascript reactjs testing jestjs mocking


    【解决方案1】:

    所以看起来我的模拟请求正在被重置。 在我的 package.json 中我必须插入这个

      "jest": {
        "resetMocks": false
      },
    

    显然 CRA 将默认值从 false 更新为 true。 similar question / answer here

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 2022-06-23
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      相关资源
      最近更新 更多