如何使用React Native库使Jest测试用例适用于React组件?

时间:2019-08-09 08:08:46

标签: reactjs react-native jestjs

我有一个使用React Native 0.55.3创建的小部件库,并且我正在使用React Native Web编译器在Web中使用该库。

当前我的设置是React + TS + React Native Widgets(使用RNW编译器)

该库在网络上运行良好,但是当我运行开玩笑的测试用例时,它开始抱怨

 Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

我尝试在配置文件中添加以下设置,但无济于事。

  "transformIgnorePatterns": [
  "node_modules/(?!react-native-my-lib)"
  ],

仍然会引发相同的错误,甚至尝试添加转换,然后将其与模拟文件配对。

我可以在我的项目中使用该库,但是测试用例每次都会失败 我们如何解决该错误?

3 个答案:

答案 0 :(得分:0)

现在我为了缓解这个问题所做的工作是模拟了RN组件,因为RN组件将在其自己的库中进行测试,而我们将在React端的布局中使用字符串对这些组件进行模拟。

我的解决方法[请让我知道这是否可行]

创建一个模拟文件

module.exports = {
  RN1COMP : '',
  RN2COMP : ''
}

在玩笑中使用模块名称映射器

  moduleNameMapper: {
    "react-native-widgets": "<rootDir>/mocks/react-native-widgets.js"
  },

答案 1 :(得分:0)

尝试这个希望能奏效!

"transformIgnorePatterns": [
      "/node_modules/(?!(react-native|redux-persist|react-navigation.*?\\.js$))"]

答案 2 :(得分:0)

在package.JSON中尝试整个配置

"jest" : {
    "preset": "react-native",
    "coveragePathIgnorePatterns": [
      "allMocks.js"
    ],
    "setupFiles": [
      "<rootDir>/jest/allMocks.js"
    ],
    "testPathIgnorePatterns": [
      "/*/*.testdata.js$"
    ],
    "transformIgnorePatterns": [
      "/node_modules/(?!(react-native|redux-persist|react-navigation.*?\\.js$))"
    ],
    "transform": {
      "\\.(jpg|jpeg|PNG|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "./fileTransformer.js"
    },
    "reporters": [
      "default",
      [
        "./node_modules/jest-html-reporter",
        {
          "pageTitle": "Test Report",
          "includeFailureMsg": true
        }
      ]
    ]
  }```