当测试反应项目时,npm测试工作,但是jest没有

问题描述 投票:0回答:2

我使用create-react-app来创建一个新的反应应用程序,并添加了几个简单的组件和测试。使用'npm test'运行测试时,运行正常。当使用jest运行时,在测试中使用导入的组件时,我会得到“意外的令牌”。例如:

import React from 'react';
import { shallow } from 'enzyme';
import App from './App';

it('renders without crashing', () => {
  shallow(<App />);
});

在测试中使用App会产生错误,但仅限于运行jest时。

javascript node.js reactjs jest
2个回答
1
投票

unexpected token错误可能是因为你没有安装babel-jest并且没有将transform密钥添加到jest.json。我希望createReactAppis doing something to hide this from you. If you want to use non-createReactApp commands (likejest`)然后我''eject'应用程序(无法撤消),以便您可以看到所有配置等。

或者你可以添加自己的jest.json,但我觉得这有两种运行测试的方法可能会让人感到困惑。


0
投票

如果你想要更多地控制它,我建议绕过create-react-app开箱即用的东西。

您可以在test中添加package.json条目,该条目主要使用jest,但允许您传递配置文件。

  "scripts": {
    ...
    "test": "jest --config jest.conf.js",
    ...
  },

然后在jest.conf.js中,您可以添加要在测试中使用的变量。 collectCoveragecoverageDirectory属性用于代码覆盖。

{
  "globals":{
    "__DEV__": true,
    "API_BASE_URL": "http://api",
    "SOME_VAR": "whatever"
    "unmockedModulePathPatterns": [
      "node_modules/react/",
      "node_modules/enzyme/"
    ]
  },
  "collectCoverage": "true",
  "coverageDirectory": "coverage"
}

然后在运行npm run test时,它将使用jest执行测试,并使用自定义配置。

© www.soinside.com 2019 - 2024. All rights reserved.