gpt4 book ai didi

javascript - React Native - Jest.mock 必须是内联函数。使用 'withNavigation' 的故障测试组件

转载 作者:行者123 更新时间:2023-11-30 11:12:26 30 4
gpt4 key购买 nike

我在我的 React Native 应用程序中使用 Jest 和 Enzyme 来测试我的组件,并且在测试 babel-plugin-jest-hoist 时我一直收到此错误:'jest.mock' 的第二个参数必须是一个内联函数。 我不太明白我做错了什么,因为我传递的是内联函数。

这是我的测试文件 (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 导航错误?如果您需要我提供更多信息,请告诉我。任何想法都会有所帮助。

最佳答案

我猜问题在于,出于所有意图和目的,您将一个对象作为第二个参数传递给 jest.mock。箭头函数位于 withNavigation 键中的对象内。

我相信您需要向它传递一个返回相同对象的箭头函数,如下所示:

jest.mock('react-navigation', () => ({ withNavigation: (component) => component}));

希望对您有所帮助!干杯。

关于javascript - React Native - Jest.mock 必须是内联函数。使用 'withNavigation' 的故障测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146079/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com