在React Native中,我使用fetch来执行网络请求,但是fetch并不是一个明确需要的模块,所以似乎不可能Jest 地模仿.

即使try 调用在测试中使用fetch的方法,也会导致:

ReferenceError:未定义提取

有没有办法在react native with Jest中测试这样的API请求?

推荐答案

在测试用例中,您可以使用Jest的mock来模拟任何想要的函数:

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

这种方法只适用于基于promise 的测试用例(参见Jest文档中的pit).

由于fetch是一个异步函数,所以需要使用pit运行所有测试(请阅读有关异步测试here的更多信息).

React-native相关问答推荐

使用NextJS映射从数组中提取用户角色

Redux将旧状态迁移到新状态

如何在使用嵌套的堆栈导航器在选项卡之间导航后弹出到堆栈顶部?

Reaction-Native-pdf文件不是PDF格式或已损坏

TextInput 中的大写文本 - react native

react native 如何更新倒置平面列表的数组中的项目

React-Native-Web 错误:rnw_blogpost.bundle.js:1414 Uncaught TypeError: Cannot read properties of undefined (reading 'isBatchingLegacy')

如何在 navigation.js 文件中的 react-navigation 中当前路由名称?

react-navigation中的React-native android后退按钮

可能的未处理promise 拒绝(id:0):错误: "getLoginData" is read-only

React-Native 是单线程执行还是多线程执行?

Invariant Violation:Chrome 不支持在本机模块上调用同步方法

如何在 mac 上卸载 react-native-cli?

中彼此相邻对齐(Align) react native

如何重置react-native 动画?

在使用 redux-persist 重新水化存储之前加载初始状态的默认值

Typescript:onPress 类型

react-native Bottom Up drawer

React Navigation 中的选项卡导航器图标

Jest TransformIgnorePatterns 所有 node_modules 用于 React-Native Preset