解析TypeError:import_react_native.AppState.removeEventListener is not a function
Jest React Native Mock AppState TypeError
问题记录
背景:通过 Jest 和 React Testing Library 对 React Native 做自动化测试
问题: 代码中出现 AppState 的使用
import { AppState } from 'react-native';
AppState.removeEventListener('change', handleAppStateChange);报错:TypeError: import_react_native.AppState.removeEventListener is not a function
jest.config.js 配置使用了 React Native 预设
module.exports = {
preset: 'react-native',
...经过排查发现是因为 React Native 提供的 jest mock 文件缺失部分方法
路径:*/react-native/jest/setup.js
.mock('react-native/Libraries/AppState/AppState', () => ({
addEventListener: jest.fn(() => ({
remove: jest.fn(),
})),
}))解决方案
项目临时方案是将 packages/react-native/jest/setup.js 拷贝下来,增加 react-native/Libraries/AppState/AppState 模块的 removeEventListener 和 currentState方法的mock
.mock('react-native/Libraries/AppState/AppState', () => ({
addEventListener: jest.fn(() => ({
remove: jest.fn(),
})),
removeEventListener: jest.fn(),
currentState: jest.fn(),
}))然后放在项目仓库中在 jest.setup.js 文件头部引入
或者在 jest.config.js 的 setupFilesAfterEnv 入口引入
最后,这个缺陷我已经给 React Native 官方仓库提了Pull Request,已经合并主分支了

以上就是解析TypeError:import_react_native.AppState.removeEventListener is not a function的详细内容,更多关于AppState TypeError解决的资料请关注脚本之家其它相关文章!
- JS报错Uncaught TypeError: XXX is not a function的解决方法
- React/vue开发报错TypeError:this.getOptions is not a function的解决
- 解决TypeError: Object of type xxx is not JSON serializable错误问题
- vue watch报错:Error in callback for watcher "xxx":"TypeError的解决方法
- 完美解决vue中报错 “TypeError: Cannot read properties of null (reading'forEach')“
相关文章
React中的useState和setState的执行机制详解
这篇文章主要介绍了React中的useState和setState的执行机制,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-03-03
React掌握openapi-typescript-codegen快速生成API客户端代码的过程
openapi-typescript-codegen是一个开源工具,用于根据OpenAPI规范自动生成TypeScript代码,包括类型定义和API客户端代码,它帮助开发者节省手动编写代码的时间,提高开发效率,感兴趣的朋友一起看看吧2024-11-11
react-native 封装选择弹出框示例(试用ios&android)
本篇文章主要介绍了react-native 封装选择弹出框示例(试用ios&android),具有一定的参考价值,有兴趣的可以了解一下2017-07-07
React 中如何将CSS visibility 属性设置为 hidden
这篇文章主要介绍了React中如何将CSS visibility属性设置为 hidden,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-05-05


最新评论