我有一个 Expo 应用程序,正在使用 SDK 28。我的团队决定我们应该更新到最新版本,这意味着更新 React Native(因为最新的 SDK 使用 RN 0.57)和 Babel。
当我们更新依赖项并修复配置文件时,Jest 开始向我们提供以下错误:
TypeError: Cannot read property 'fetch' of undefined
at node_modules/react-native/Libraries/vendor/core/whatwg-fetch.js:6:12
at Object.<anonymous> (node_modules/react-native/Libraries/vendor/core/whatwg-fetch.js:486:3)
at Object.<anonymous> (node_modules/jest-expo/src/setup.js:125:16)
经过几天的调试我发现这与babel-jest
的预处理器无法正常工作,即使我遵循了他们的安装docs https://github.com/facebook/jest/blob/master/README.md#using-babel.
我进行了更多研究,发现有一个解决方法GitHub 问题线程 https://github.com/expo/expo/issues/2595#issuecomment-440966998.
实施解决方法,并添加babel-葫芦 https://www.npmjs.com/package/babel-plugin-jest-hoist to my babel.config.js
,以便测试开始运行。
然而,Jest 的行为很奇怪,而且覆盖数据也不正确(它会将某些行视为未覆盖,即使我们确实对它们进行了测试)。
我想知道如何正确配置 Jest 以兼容 Expo SDK 32。
这些是相关的配置文件(设置为使用前面提到的解决方法)。
包.json*
"dependencies": {
"@babel/preset-env": "^7.3.1",
"@expo/vector-icons": "6.3.1",
"expo": "^32.0.0",
"prop-types": "15.6.2",
"react": "16.5.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
"sentry-expo": "~1.9.0"
...
},
"devDependencies": {
"@babel/core": "^7.2.2",
"babel-eslint": "9.0.0",
"babel-plugin-jest-hoist": "^24.0.0",
"babel-preset-expo": "^5.0.0",
"enzyme": "3.8.0",
"enzyme-adapter-react-16": "^1.8.0",
"jest-expo": "^32.0.0",
"metro-react-native-babel-preset": "^0.51.1",
"react-dom": "^16.5.1",
...
},
"jest": {
"preset": "jest-expo",
"transform": {
"^.+\\.js$": "<rootDir>/jest.preprocessor.js"
},
"setupFiles": [
"<rootDir>/src/jest.setup.js"
],
...
}
* 省略了一些依赖项。
babel.config.js
module.exports = {
presets: [
'babel-preset-expo',
'module:metro-react-native-babel-preset',
'module:react-native-dotenv',
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
sourceMaps: true,
plugins: [
'jest-hoist',
'@babel/transform-react-jsx-source',
],
};