我在 react 功能组件中调用 api。我正在编写组件的单元测试用例。我使用 jest-fetch-mock 模拟了 fetch。global.fetch = require('jest-fetch-mock');
组件.ts
const Component = () => {
useEffect(() => {
return fetch(
'url',
)
.then(response => response.json())
.then(json => {
setApiResult(json);
setFilterResult(json?.videos);
})
.catch(error => {
console.error(error);
});
}, []);
}
有谁知道如何开玩笑地模拟这个组件的 fetch 响应。
最佳答案
这个来自jest-fetch-mock
直接文档
setupJest.js
项目根目录下的文件,内容如下。 require('jest-fetch-mock').enableMocks()
setupJest.js
文件到 jest.config.js 或 package.json 无论你的 jest 配置是什么。 "jest": {
"automock": false,
"setupFiles": [
"./setupJest.js"
]
}
现在您可以使用 fetch
和 fetchMock
在全局范围内describe('testing Component', () => {
beforeEach(() => {
fetch.resetMocks()
})
it('testing something...', () => {
fetch.mockResponseOnce(JSON.stringify({ data: '12345' }))
const container = render (<Component/>)
// expect statement can be wrong.
expect(container.getByText(/12345/).toBeDefined())
})
});
关于javascript - 如何使用 jest-fetch-mock 模拟获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72718623/