【问题标题】:setupTests.js not loading automatically in CRA react appsetupTests.js 未在 CRA 反应应用程序中自动加载
【发布时间】:2019-05-07 15:07:17
【问题描述】:

我已经读到 src/setupTests.js 应该在每次测试之前加载,但我仍然让每个测试都失败并出现错误:

“Enzyme 内部错误:Enzyme 需要配置适配器,但没有找到。”

这是我的 src/setupTests.js

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'whatwg-fetch';

Enzyme.configure({ adapter: new Adapter() });

这是我的 package.json:

"devDependencies": {
"babel-core": "^6.26.3",
"babel-jest": "^23.6.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"coveralls": "^3.0.2",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.6.0",
"enzyme-to-json": "^3.3.4",
"jest": "^23.6.0",
"react-test-renderer": "^16.5.2",
"redux-mock-store": "^1.5.3",
"regenerator-runtime": "^0.12.1",
"whatwg-fetch": "^3.0.0"
}

我正在通过npm run test 运行“测试”脚本

"scripts": {
  "test": "jest",
  "test:watch": "jest --watch",
  "test:updateSnapshots": "jest --updateSnapshot"
}

我用以下某种形式开始每个测试文件:

import React from 'react';
import { shallow } from 'enzyme';

我正在使用 react-scripts 2.1.1 使用 React 16

我是否做错了任何人都能看到的事情?

【问题讨论】:

  • 您是否尝试重新启动测试运行器?这与我的工作设置几乎相同。
  • @DeveloperDavo 我已经删除了我的 node_modules 文件夹并npm installed 多次。这算作重新启动我的测试运行器吗?在这种情况下,测试运行器到底是什么?
  • 间接:)。重新运行npm run test(或npm test)可以解决问题,但我现在看到问题已经得到解答。

标签: reactjs jestjs enzyme create-react-app babel-jest


【解决方案1】:

将以下内容添加到 package.json 时是否有效

"scripts": {
  ...
  "test": "react-scripts test",
  ...

}

【讨论】:

  • 这行得通。知道为什么吗?我猜“Jest”命令绕过了 CRA 默认值?
  • 我相信这是因为 react-scripts test 创建了一个 Jest 配置,而运行 jest 可以绕过该配置。这是source code
【解决方案2】:

更新 package.json。

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test setupFile ./src/setupTests.js",
    "eject": "react-scripts eject"
  }

【讨论】:

    【解决方案3】:

    我在这里遇到了同样的错误,但还有另一个原因:

    我有一个文件名错字

    • src/setupTest.js 而不是 src/setupTest*s*.js

    然后默认 CRA (creat-react-app) package.json 命令将 Adapter 加载到您的测试中:

    • "test": "react-scripts test"

    【讨论】:

    • 你帮我节省了一个小时的调试时间,谢谢!
    【解决方案4】:

    它应该适用于这种配置。由于相同的配置在我的应用程序中有效。尝试将 import 放入测试文件中。

    import "../setupTests"
    

    有时这可行。

    【讨论】:

    • 我之前已经在我的 package.json 中放置了一个“setupTestFrameworkScriptFile”覆盖并且可以工作,但是它破坏了 vs 代码调试器,因为它不应该是必需的。
    【解决方案5】:

    如果您在 create-react-app 的 npm test 脚本中的 watch 模式下创建了 setupTests.js 文件,那么您需要退出 watch 模式并重新启动它才能开始工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 2022-01-05
      • 2015-06-01
      • 2020-12-19
      • 2019-08-14
      • 2018-02-05
      • 2016-02-02
      相关资源
      最近更新 更多