问题一:
Unexpected token in 'node_modules\@react-navigation\stack\lib\commonjs\views\assets\back-icon.png
原因:
jest默认不对node_modules进行转译,但是有时候第三方库(eg. @react-navigation)以未转译的形式发布,所以我们需要对node_modules进行转译。
解决方案:
jest.config.js中设置
module.exports = {
// 未配置时,默认值为["/node_modules/", "\\.pnp\\.[^\\\/]+$"]
"transformIgnorePatterns": [],
};
问题二:
[@RNC/AsyncStorage]: NativeModule: AsyncStorage is null.
原因:异步存储模块与其NativeModule
部分紧密耦合 - 它需要一个正在运行的 React Native 应用程序才能正常工作。为了在测试中使用它,您必须提供其单独的实现。
解决方案:
1. 在项目跟目录下创建jest目录
2. 在jest目录下创建setup.js
3. 在该文件中输入
jest.mock('@react-native-async-storage/async-storage', () =>
require('@react-native-async-storage/async-storage/jest/async-storage-mock')
);
意思是用'@react-native-async-storage/async-storage/jest/async-storage-mock'文件中的导出内容mock '@react-native-async-storage/async-storage'的导出内容。
4. 在jest.config.js中加入配置
module.exports = {
"setupFiles": ["<rootDir>/jest/setup.js"],
};
问题三:
Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'RNCClipboard' could not be found. Verify that a module by this name is registered in the native binary.Bridgeless mode: false. TurboModule interop: false. Modules loaded: {"NativeModules":["PlatformConstants","DeviceInfo","I18nManager"],"TurboModules":[],"NotFound":["RNCSafeAreaContext","NativeAnimatedModule","SoundManager","RNSModule","RNVectorIcons","RNCClipboard"]}
原因:可能与问题二一致,需要一个正在运行的 React Native 应用程序才能正常工作。
解决方案:
和上文类似,也是用mock的方式解决。
在jest/setup.js中加入
jest.mock('@react-native-clipboard/clipboard', () =>
require('@react-native-clipboard/clipboard/jest/clipboard-mock.js')
);
问题四:
Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'RNGestureHandlerModule' could not be found. Verify that a module by this name is registered in the native binary.Bridgeless mode: false. TurboModule interop: false. Modules loaded: {"NativeModules":["PlatformConstants","DeviceInfo","I18nManager","SourceCode","KeyboardObserver","ImageLoader"],"TurboModules":[],"NotFound":["RNCSafeAreaContext","NativeAnimatedModule","SoundManager","RNSModule","RNVectorIcons","LogBox","ReanimatedModule","FrameRateLogger","RNGestureHandlerModule"]}
解决方案:
在jest/setup.js中加入
import 'react-native-gesture-handler/jestSetup';
问题五:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. From __tests__/App.test.tsx.
at Object.get Platform [as Platform] (node_modules/react-native/index.js:225:12)
at node_modules/@react-navigation/bottom-tabs/lib/commonjs/utils/useIsKeyboardShown.js:63:22
at commitHookEffectListMount (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8822:30)
原因:在执行import的时候jest环境已经被拆除。已经被拆除的原因不明,有佬知道可以解答一下。
解决方案:
在jest.config.js中加入
{
testEnvironment: 'jsdom',
};
把测试环境从默认的node环境切换到浏览器环境。