如何在与Jest的react-native中使用模拟的fetch()对API调用进行单元测试
在React Native中,我使用fetch
来执行网络请求,但是fetch
不是明确要求的模块,因此似乎无法在Jest中进行模拟.
In React Native I use fetch
to perform network requests, however fetch
is not an explicitly required module, so it is seemingly impossible to mock in Jest.
即使尝试调用在测试中使用fetch
的方法也会导致:
Even trying to call a method which uses fetch
in a test will result in:
ReferenceError:提取未定义
ReferenceError: fetch is not defined
有没有一种方法可以在Jest的本机响应中测试此类API请求?
Is there a way to test such API requests in react native with Jest?
在测试用例中,您可以使用Jest的模拟对象来模拟所需的任何功能:
Inside your test case you can mock any function you want by using Jest's mocks:
fetch = jest.fn(() => Promise.resolve());
这种方法仅适用于基于承诺的测试用例(请参阅Jest文档中的pit
).
This approach works only for the promise-based test cases (see pit
in the Jest docs).
至于fetch
是一个异步函数,您需要使用pit
运行所有测试(了解有关异步测试的更多信息
As far as fetch
is an async function, you need to run all your tests using pit
(read more about async tests here).