【问题标题】:When testing react project npm test works but jest doesn't测试反应项目时 npm test 有效,但 jest 无效
【发布时间】:2018-06-09 20:21:50
【问题描述】:

我使用 create-react-app 创建了一个新的 react 应用,并添加了几个简单的组件和测试。使用“npm test”运行测试时,它们运行良好。在开玩笑运行时,在测试中使用导入的组件时,我得到“意外令牌”。例如:

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

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

测试中 App 的使用给出了错误,但仅在运行 jest 时。

【问题讨论】:

  • 你开什么玩笑?当你运行 npm test 时 create-react-app 使用 jest
  • 大部分时间只是在玩。试图找出差异。看起来 create-react-app 在 package.json 中创建了一些名为“react-scripts test --env=jsdom”的东西。我猜这在下面使用玩笑?我想要更多的控制,因为它与观察者一起运行,我并不总是想这样做。我也想要报道

标签: javascript node.js reactjs jestjs


【解决方案1】:

如果您想对此进行更多控制,我建议您使用 create-react-app 绕过开箱即用的内容。

您可以在package.json 中添加一个test 条目,该条目实际上将使用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 执行测试,并带有自定义配置。

【讨论】:

    【解决方案2】:

    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,但我觉得这可能会让你感到困惑,因为有 2 种运行测试的方式。

    【讨论】:

      猜你喜欢
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      相关资源
      最近更新 更多