我一直在尝试在新的React Native应用中设置react-navigation
。当我使代码/屏幕正常工作时,Jest在按照v4 docs添加库之后,导致我遇到问题。
我安装了react-navigation
,react-native-reanimated
,react-native-gesture-handler
和react-native-screens@^1.0.0-alpha.23
。然后,我进入ios
文件夹并运行pod install
。因为我使用的是React Native v0.61,所以它们应该已经自动链接了。
运行默认的Jest测试时,出现类似以下错误:
✓ renders correctly (106ms)
console.warn node_modules/react-native/Libraries/Animated/src/NativeAnimatedHelper.js:270
Animated: `useNativeDriver` is not supported because the native animated module is missing. Falling back to JS-based animation. To resolve this, add `RCTAnimation` module to this app, or remove `useNativeDriver`. More info: https://github.com/facebook/react-native/issues/11094#issuecomment-263240420
我搜索了此错误,大多数建议的答案是将其放入我的测试文件中:
jest.mock('NativeAnimatedHelper');
但是,当我尝试这样做时,Jest抱怨这样的错误:
FAIL __tests__/App-test.tsx
● Test suite failed to run
Cannot find module 'NativeAnimatedHelper' from 'App-test.tsx'
6 | import renderer from 'react-test-renderer'
7 |
> 8 | jest.mock('NativeAnimatedHelper')
| ^
9 |
10 | it('renders correctly', () => {
11 | renderer.create(<App />)
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
at Object.<anonymous> (__tests__/App-test.tsx:8:1)
一段时间以来,我一直在尝试各种事情,任何帮助/建议将不胜感激!
版本:
Node: 10.16.1
npm: 6.11.3
"react": "^16.9.0",
"react-native": "0.61.1",
"react-native-gesture-handler": "^1.4.1",
"react-native-reanimated": "^1.3.0",
"react-native-screens": "^1.0.0-alpha.23",
"react-navigation": "^4.0.10",
"react-navigation-stack": "^1.9.3",
"babel-jest": "^24.1.0"
"jest": "^24.1.0"
"react-test-renderer": "^16.9.0"
最佳配置:
{
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"setupFiles": [
"./node_modules/react-native-gesture-handler/jestSetup.js"
],
"transformIgnorePatterns": [
"node_modules/(?!((jest-)?react-native|react-navigation|@react-navigation/.*))"
]
}
}
答案 0 :(得分:8)
更改
jest.mock('NativeAnimatedHelper');
收件人
jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper');
答案 1 :(得分:5)
对于 RN 64,它应该是 jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper');
答案 2 :(得分:3)
尽管公认的答案似乎对人们有用,并且是推荐的方法之一,但对我却没有用。另外,它也不理想,因为在下一个版本中路径可能会更改。
按照此blog post中提到的实施方式,我能够适当地模拟所有单独的本机模块。
实际上,我不得不通过在react-native.js
内添加一个test/__mocks
文件来模拟react-native接口,并将模拟后的模块导出为:
import * as ReactNative from "react-native";
export const Image = "NativeAnimatedHelper";
export default Object.setPrototypeOf(
{
NativeAnimatedHelper
},
ReactNative
);
您可以根据需要在测试中添加任意多个导出。
答案 3 :(得分:2)
React Native v0.64.0
src 文件夹已从 Animated
中删除您需要从模拟路径中删除 src:
Before:
jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper');
After:
jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper');
答案 4 :(得分:0)
我不想每次使用NativeAnimatedHelper
时都这样做,因此我将模拟添加到了jestSetup.js
文件中。
// test/jestSetup.js
jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper');
该文件应包含在jest.config.js
文件中
module.exports = {
setupFiles: [
'<rootDir>/tests/jestSetup.js',
],
};