[英]Test multiple fetches in componentDidMount with Jest/Enzyme
I am starting to learn more about testing for React using Jest/Enzyme and I am trying to learn how to test api calls that use fetch. 我开始学习有关使用Jest / Enzyme测试React的更多信息,并且尝试学习如何测试使用fetch的api调用。
I have a fetch call in a componentDidMount()
method and I am able to test that correctly. 我在
componentDidMount()
方法中有一个访存调用,并且能够正确测试它。 In the beforeEach()
method, I have a window.fetch
method that creates the mock fetch. 在
beforeEach()
方法中,我有一个window.fetch
方法来创建模拟提取。 Here is an example: 这是一个例子:
beforeEach(() => {
mockData = /* mock data */
// mock fetch call
window.fetch = jest.fn().mockImplementation(() => Promise.resolve({
json: () => Promise.resolve({
data: mockData,
})
}));
component = shallow(<Component />);
});
However, I have another component that has two fetch calls in the componentDidMount()
method, and I'm wondering how I can mock each fetch call individually. 但是,我有另一个组件在
componentDidMount()
方法中具有两个fetch调用,并且我想知道如何分别模拟每个fetch调用。 Is it possible to have two window.fetch
calls or somehow pass in a url for the fetch? 是否可以有两个
window.fetch
调用或以某种方式传递URL以进行提取?
I am still new to this, so any help would be appreciated! 我对此还很陌生,因此不胜感激!
Thanks! 谢谢!
You can use fetch-mock library to mock each request separately. 您可以使用fetch-mock库分别模拟每个请求。 Suppose you're requesting 2 URLs and you want to return
mockData
in the request to the first URL, and just 404 status in the second one. 假设您要请求2个URL,并且要将请求中的
mockData
返回到第一个URL,而在第二个URL中仅返回404状态。 Your example code mocked with fetch-mock may look like this: 使用fetch-mock模拟的示例代码可能如下所示:
import fetchMock from "fetch-mock"; beforeEach(() => { mockData = { /* mock data */ }; fetchMock.mock("/first/url", mockData); fetchMock.mock("/second/url", 404); component = shallow(<Component />); }); /* You should also restore the original fetch in afterEach */ afterEach(() => { fetchMock.restore(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.