首页 > 解决方案 > 开玩笑:测试套件无法运行(Expo SDK 需要 Expo 才能运行)

问题描述

我很难让 Jest 启动并运行我的 RN expo 项目(所以我可以玩耍和学习它)。

 FAIL  screens/HomeScreen.test.js
  ● Test suite failed to run

    The Expo SDK requires Expo to run. It appears the native Expo modules are unavailable and this code is not running on Expo. Visit https://docs.expo.io to learn more about developing an Expo project.

      at Object.<anonymous> (node_modules/expo/src/environment/validate.ts:11:9)
      at Object.require (node_modules/expo/build/Expo.js:278:1)

 FAIL  __tests__/App-test.js
  ● Test suite failed to run

    The Expo SDK requires Expo to run. It appears the native Expo modules are unavailable and this code is not running on Expo. Visit https://docs.expo.io to learn more about developing an Expo project.

      at Object.<anonymous> (node_modules/expo/src/environment/validate.ts:11:9)
      at Object.require (node_modules/expo/build/Expo.js:278:1)

 PASS  components/__tests__/StyledText-test.js (7.769s)

Test Suites: 2 failed, 1 passed, 3 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        10.477s
Ran all test suites.

包.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "eject": "expo eject",
    "test": "jest --watchAll"
  },
  "jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
      "node_modules/(?!((jest-)?react-native|react-clone-referenced-element|expo(nent)?|@expo(nent)?/.*|react-navigation|sentry-expo))"
    ]
  },
  "dependencies": {
    "@expo/samples": "2.1.1",
    "expo": "^32.0.0",
    "react": "16.5.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
    "react-navigation": "^3.0.9"
  },
  "devDependencies": {
    "babel-preset-expo": "^5.0.0",
    "jest": "^24.7.1",
    "react-test-renderer": "^16.8.6"
  },
  "private": true
}

.babelrc

{
  "presets": ["react-native"]
}

标签: react-nativejestjsexpobabel-jest

解决方案


我认为您的错误出在文件中的jest密钥中,package.json并且您的 Babel 配置预设也是错误的。

首先添加"jest-expo": "^32.0.0"到您的devDependencies(因为您使用的是 SDK 32),然后您必须将您的开玩笑密钥更改package.json为:

"jest": {
    "preset": "jest-expo",
}

将您的.babelrc预设键更改为:presets: ['babel-preset-expo']。或者删除它并创建一个babel.config.js包含以下内容的文件(推荐):

module.exports = api => {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
  };
};

如果这仍然不起作用,请查看jest-expo项目,它应该为您指明正确的方向。或者发表评论,我将编辑答案以帮助您。


推荐阅读