【问题标题】:Test suite failed to run with @react-navigation/stack测试套件无法使用 @react-navigation/stack 运行
【发布时间】:2021-06-05 09:39:46
【问题描述】:

我开始在 React Native 应用程序中编写单元测试。我使用以下命令在 Typescript 中创建了新项目。

npx react-native init rn_jest --template 反应原生模板打字稿

当我在项目的根目录中执行 npm test 时,我得到了以下结果

通过测试/App-test.tsx (7.472s) ✓ 正确呈现 (4329ms) 测试套件:1 个通过,共 1 个测试:1 个通过,共 1 个 快照:0 总时间:7.64 秒运行所有测试套件。

接下来我将React Navigation集成到应用程序中并再次执行npm测试,但这一次我得到以下错误

FAIL tests/App-test.tsx ● 测试套件未能运行

/Users/macbookpro/Documents/Manheium_Express/rn_jest/node_modules/@react-navigation/stack/lib/commonjs/views/assets/back-icon.png:1
�PNG

SyntaxError: Invalid or unexpected token

  at Runtime._execModule (node_modules/jest-runtime/build/index.js:1157:58)

控制台错误 未找到 react-native-gesture-handler 模块。确保您在本机平台上运行您的应用程序并且您的代码已链接 正确(cd ios && pod install && cd ..)。

For installation instructions, please refer to https://docs.swmansion.com/react-native-gesture-handler/docs/#installation

  at Object.<anonymous> (node_modules/react-native-gesture-handler/lib/commonjs/RNGestureHandlerModule.ts:5:3)

测试套件:1 次失败,总共 1 次测试:总共 0 次快照:0 总时间:3.229 秒运行所有测试套件。 npm 错误!测试失败。 有关详细信息,请参见上文。

我检查了这个link 并没有找到任何解决方案。这是 App-test.tsx 文件中的代码

import 'react-native';
import React from 'react';
import App from '../App';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  renderer.create(<App />);
});

下面是package.json

 "dependencies": {
    "@react-native-community/masked-view": "^0.1.10",
    "@react-navigation/native": "^5.9.3",
    "@react-navigation/stack": "^5.14.3",
    "react": "16.13.1",
    "react-native": "0.63.4",
    "react-native-gesture-handler": "^1.10.3",
    "react-native-reanimated": "^2.0.0",
    "react-native-safe-area-context": "^3.1.9",
    "react-native-screens": "^2.18.1"
  },

我也关注了这个link,但没有运气。如果有人在单元测试中使用 jest 解决了这个问题,请帮助我

【问题讨论】:

    标签: react-native jestjs react-navigation-v5


    【解决方案1】:

    我按照 Jest 文档处理了这个问题:

    Testing with Jest

    并遵循此文档中的处理静态资产部分:

    Handling Static Assets

    我的 package.json 看起来像:

      "jest": {
        "preset": "react-native",
        "moduleFileExtensions": [
          "ts",
          "tsx",
          "js",
          "jsx",
          "json",
          "node"
        ],
        "setupFiles": [
          "<rootDir>/jest/setup.js"
        ],
        "moduleNameMapper": {
          "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
          "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
        }
    

    我终于跑了:

    yarn jest
    

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 2021-10-09
      • 2020-11-25
      • 2020-11-05
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多