如何在与Jest的react-native中使用模拟的fetch()对API调用进行单元测试 [英] How to unit test API calls with mocked fetch() in react-native with Jest

查看:207
本文介绍了如何在与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).

这篇关于如何在与Jest的react-native中使用模拟的fetch()对API调用进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆