花了两天的时间研究之后,我终于耗尽了想法。
问题是使用withNavigation
中的React-Navigation
的组件。
当我运行Jest
时,它抱怨指向withNavigation
的令牌意外导出(React-Navigation)。
由于其他第三方库(例如Native Base
)存在相同的问题,因此我得出结论transformIgnorePatterns
必须存在一个问题。例如,我尝试了这个solution之间的相似之处,其中有许多相似之处。我也尝试调整babel.config
,如GitHub上另一篇文章所建议。没用!也许有人有主意?请不要我使用TypeScript
。
如果我的Jest
是package.json
部分,
...
"jest": {
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
"\\.(ts|tsx)$": "ts-jest"
},
"globals": {
"ts-jest": {
"tsConfig": "tsconfig.jest.json"
}
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"transformIgnorePatterns": [
"node_modules/(?!react-native|native-base|react-navigation|react-native-fabric)"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
}
jest.config.js:
module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
tsconfig.jest.json:
{
"extends": "./tsconfig",
"compilerOptions": {
"jsx": "react",
"module": "commonjs"
}
}
tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"noImplicitAny": true,
"jsx": "react",
"lib": ["es6"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext"
},
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}
babel.config.js:
module.exports = {
presets: [
'module:metro-react-native-babel-preset',
'@babel/preset-typescript',
],
};
组件(测试):
imports ...
type Props = {}
const Test: React.FC<Props> = ({}) => {
return (
<View testID="test" style={styles.container}>
<View>
<Text testID="home">Home</Text>
<ButtonNavigate title="Home" navigateTo="About" />
</View>
</View>
);
};
export default withNavigation(Test);
测试:
import React from 'react';
import {render, fireEvent} from 'react-native-testing-library';
import Test from '../Test';
// NativeAnimatedHelper is not mocked by default on react native's jest setup file.
jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper');
//jest.mock('react-navigation', () => ({withNavigation: component => component}));
describe('Test', () => {
test('rendering a component that uses withNavigation', () => {
const {getByTestId} = render(
<Test navigation={navigation}></Test>,
);
expect(getByTestId('test').toBeDefined());
});
});
如果有人可以帮助,请先感谢。
答案 0 :(得分:3)
这对我有用:
jest.mock('react-navigation', () => ({
withNavigation: (Component) => (props) => (
<Component navigation={{ navigate: jest.fn() }} {...props} />
),
}))
告诉我,如果它也对您有用。