当前位置: 动力学知识库 > 问答 > 编程问答 >

How to unit test API calls in react-native with Jest

问题描述:

In react-native we use fetch to perform network requests, however fetch is not an explicitly required module, so is seemly impossible to mock in Jest. Even trying to call a method which which uses fetch in a test will result in ReferenceError: fetch is not defined.

Is there anyway to test API requests in react native with Jest? Thanks

网友答案:

Inside your test case you can mock any function you want by using Jest's mocks:

fetch = jest.fn(() => new Promise(resolve => resolve()));

This approach works only for the promise-based test cases (see pit in the Jest docs).

As far as fetch is an async function, you need to run all your tests using pit (read more about async tests here).

网友答案:

Rather than rolling your own mock, you can use the jest-fetch-mock npm package to override the global fetch object. That package allows you to set up fake responses and verify sent requests. See that link for extensive usage examples.

分享给朋友:
您可能感兴趣的文章:
随机阅读: