7

尝试运行测试用例代码时出现错误。我正在使用 react native 和 jest 。在升级 0.40 之前一切正常。现在是 0.42 我所有的测试用例都停止工作并在错误后出现错误。

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React, { Component, Children, PropTypes } from 'react';
                                                                                             ^^^^^^
    SyntaxError: Unexpected token import

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at Object.<anonymous> (node_modules/react-native-root-siblings/lib/AppRegistryInjection.js:3:22)
      at Object.<anonymous> (node_modules/react-native-root-siblings/lib/SiblingsManager.js:3:27)

这是我的.babelrc代码

{
    "presets": [
        "react-native"
    ],
    "plugins": [
        "transform-decorators-legacy"
    ]
}

我没有得到什么问题。

4

2 回答 2

4

我在 0.42 时遇到了同样的问题。我敲了敲头,直到找到一个解决方案。

您需要在package.json中编写忽略。我的例子:

"jest": {
        "preset": "react-native",
        "setupFiles": [
            "<rootDir>/src/config/jest.js"
        ],
        "transformIgnorePatterns": [
            "<rootDir>/(node_modules)/(?!react-native|react-navigation|bugsnag-react-native)"
        ],
        "transform": {
            "^.+\\.js$": "<rootDir>/node_modules/babel-jest"
        }

我的/config/jest.js看起来像:

jest.mock('Linking', () => ({
  addEventListener: jest.fn(),
  removeEventListener: jest.fn(),
  openURL: jest.fn(),
  canOpenURL: jest.fn(),
  getInitialURL: jest.fn().mockImplementation(() => new Promise((resolve) => resolve()))
}));

jest.mock('mobx-react/native', () => require('mobx-react/custom'));
jest.mock('react-native-mixpanel', () => ({
  sharedInstanceWithToken: jest.fn(),
  trackWithProperties: jest.fn()
}));
jest.mock('bugsnag-react-native', () => ({
  Client: jest.fn(),
  Configuration: jest.fn()
}));

我不保证这可以直接解决您的所有问题。然而,这个想法是忽略所有“恶人”(在你的情况下是react-native-root-siblings),从而避免此类错误消息。

于 2017-03-31T10:49:32.440 回答
2

我得到了解决方案

"jest": {
        "preset": "react-native",
        "transformIgnorePatterns": [
          "node_modules"
        ],
        "coveragePathIgnorePatterns": [
          "node_modules"
        ],
        "modulePathIgnorePatterns": [
          "node_modules"
        ]
      },

在我的devDependencies中我添加了"react-addons-test-utils", "react-dom",

"devDependencies": {
    "babel-core": "^6.17.0",
    "babel-eslint": "^7.2.1",
    "babel-jest": "^19.0.0",
    "babel-loader": "^6.2.5",
    "babel-plugin-transform-decorators": "^6.13.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2017": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-react-native": "^1.9.1",
    "babel-preset-stage-0": "^6.16.0",
    "enzyme": "^2.8.0",
    "jest": "^19.0.2",
    "npm": "^4.4.4",
    "react-addons-test-utils": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-test-renderer": "^15.4.2"
}

这解决了所有问题。

于 2017-04-04T05:03:33.950 回答