【问题标题】:Can either run React App or tests for it with babel-jest可以运行 React App 或使用 babel-jest 对其进行测试
【发布时间】:2020-03-11 02:56:45
【问题描述】:

我正在尝试为现有的 React 应用程序设置测试。我们正在使用React 16.8.13 经过一番挣扎,我已经成功了。为此,我必须安装 jest 24.9.0babel-jest 24.9.0。测试运行良好,我得到了覆盖率报告。但是,当我运行 yarn start 时出现错误:

The react-scripts package provided by Create React App requires a dependency:

  "babel-jest": "23.6.0"

Don't try to install it manually: your package manager does it automatically.
However, a different version of babel-jest was detected higher up in the tree:

  /<Path to my App>/node_modules/babel-jest (version: 24.9.0) 

devDependencies 中删除jestbabel-jest 解决了这个问题,但现在运行yarn test 给我一个错误:

No tests found
In /<Path to my App>
  32 files checked.
  testMatch:  - 32 matches
  testPathIgnorePatterns: /node_modules/ - 32 matches
  testRegex: (\/tests\/.*\.test)\.[jt]sx?$ - 0 matches
Pattern:  - 0 matches
error Command failed with exit code 1.

我需要做什么才能让应用程序和测试都可以运行?

【问题讨论】:

    标签: reactjs jestjs babel-jest


    【解决方案1】:

    根据No tests found,您的测试似乎不在正确的文件夹中。它们应该位于src 中名为__tests__ 的文件夹中,并具有test.jsspec.js 后缀。

    有关更多信息,请参阅此答案:Create React App cannot find tests

    【讨论】:

    • 我的测试在tests 文件夹中,而不是在__tests__ 中。我正在使用testRegex: (\/tests\/.*\.test)\.[jt]sx?$ 覆盖您提到的默认值。如果我从 jest.config 中删除 testRegex,实际上可以找到测试,但在 app 目录中的任何位置,而不是我想要的仅在一个文件夹中。所以显然这个配置适用于 24.9 版本,但从外观上看不适用于 23.6。
    • 您是否尝试升级到最新的create-react-app?看起来像是在开玩笑 24.9.0 github.com/facebook/create-react-app/blob/master/…
    • 我错了 testRegex 不工作。它确实有效,它确实在我的 tests 目录中查找测试文件,但它似乎无法将 TypeScript 文件识别为测试文件。一旦我将我的.test.tsx 文件重命名为.test.js.test.jsx,它就会找到它,但如果它是.test.tsx,它会显示0 个匹配项。有任何想法吗?也许我需要添加一些东西来告诉它识别 TypeScript?
    • 奇怪,那个正则表达式看起来应该匹配.test.tsx。您可能需要像 basarat.gitbooks.io/typescript/docs/testing/jest.html 这样设置 jest 配置 - 尽管我认为 Create React App 可能会限制您在 jest 配置中可以执行的操作...
    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 2019-11-02
    • 2018-09-07
    • 2019-02-24
    • 2019-07-07
    • 1970-01-01
    • 2020-07-17
    相关资源
    最近更新 更多