【发布时间】: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