我在我的React Native应用程序中使用Jest和Enzyme来测试我的组件,并且在测试babel-plugin-jest-hoist: The second argument of 'jest.mock' must be an inline function.
时一直出现此错误,我不太了解自己在做什么错,因为我通过了内联功能。
这是我在测试文件(search-screen.tests.js)中的代码:
// All necessary imports here
jest.mock('react-navigation', ({ withNavigation: (component) => component}));
describe("Search screen renders appropriately and function work", () => {
it("renders correctly", () => {
const searchScreen = renderer.create(<SearchScreen />).toJSON();
expect(searchScreen).toMatchSnapshot();
});
});
我使用了这个stack overflow post for reference
我尝试模拟react-navigation
的主要原因是因为我的搜索屏幕组件是使用'withNavigation'导出的(例如:export default withNavigation(SearchScreen)
),如果我不这样做,它将破坏很多测试尝试这样做,这是正确的做法吗?
这里也是我的package.json文件,以防万一。
{
"name": "app",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"ios-build": "sh scripts/ios/build-ipa.sh",
"test": "jest"
},
"dependencies": {
"axios": "0.18.0",
"prop-types": "15.6.2",
"react": "16.4.1",
"react-native": "0.56.0",
"react-native-cookies": "3.3.0",
"react-native-elements": "0.19.1",
"react-native-google-analytics-bridge": "6.0.1",
"react-native-maps": "0.21.0",
"react-native-snackbar": "0.5.1",
"react-native-vector-icons": "4.6.0",
"react-native-version-number": "0.3.4",
"react-navigation": "2.9.1",
"rxjs": "6.2.2"
},
"devDependencies": {
"babel-jest": "23.4.0",
"babel-preset-react-native": "5.0.2",
"@babel/core": "^7.0.0-beta.47",
"@babel/preset-env": "^7.0.0-beta.47",
"@babel/preset-flow": "^7.0.0-beta.47",
"babel-core": "^7.0.0-beta.47",
"babel-eslint": "^8.2.5",
"babel-loader": "^7.1.5",
"babel-runtime": "^6.26.0",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.6.0",
"jest": "23.4.0",
"react-dom": "^16.6.0",
"react-test-renderer": "16.4.1"
},
"jest": {
"preset": "react-native",
"transformIgnorePatterns": [
"node_modules/(?!react-native|native-base|react-navigation)"
],
"setupTestFrameworkScriptFile": "./setupTests.js",
"setupFiles": [
"./setupTests.js"
]
}
}
那么我该怎么做才能停止收到Jest的react-navigation错误?让我知道您是否需要我的更多信息。任何想法都会有所帮助。
答案 0 :(得分:2)
我猜测问题是,出于所有意图和目的,您正在将对象作为第二个参数传递给jest.mock。箭头功能位于withNavigation键中的对象内。
我相信您需要向其传递一个箭头函数,该函数将返回相同的对象,如下所示:
jest.mock('react-navigation', () => ({ withNavigation: (component) => component}));
我希望这会有所帮助!干杯。