[英]How to mock fetch response using jest-fetch-mock
我在反應功能組件中調用 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
docs
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())
})
});
這是使用 axios 的小例子
jest.mock("axios");
it('mock data', async () => {
render(<Abc />);
axios.get.mockResolvedValueOnce(data); // data is your static object
// rest code goes here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.