【问题标题】:How to exclude node_modules from create-react-app testing?如何从 create-react-app 测试中排除 node_modules?
【发布时间】:2018-06-07 07:21:14
【问题描述】:

我想使用 jest 对我的 create-react-app 进行测试。

其中一个 node_modules 有测试错误,

但我不想开玩笑地使用 node_modules 文件夹。

documentation 中,我找到了配置属性“collectCoverageFrom”并尝试在我的 package.json 中使用它:

  ....
  "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test --env=jsdom ",
        "eject": "react-scripts eject"
  },
  "jest": {
        "collectCoverageFrom": [
            "!/node_modules/*"
         ]
  }

但没有任何改变。

【问题讨论】:

  • @Andy 开箱即用,Create React App 仅支持覆盖这些 Jest 选项: • collectCoverageFrom • coverageReporters • coverageThreshold • snapshotSerializers。
  • 那么我很惊讶它没有忽略你的node_modules文件夹。
  • 哦,它忽略了你的模块文件夹,但你的测试依赖于一些不能正常工作的东西。这是一个不同的问题。
  • 它由 node_module 工作,我不想开玩笑地分析它(

标签: javascript testing jestjs create-react-app package.json


【解决方案1】:

没有覆盖范围。

您的一个组件正在使用react-mic 包提供通过window.AudioContext 访问音频。

你有不同的方法来解决它。

  1. 你可以模拟window.AudioContext。真的很难实现。我真的不建议你这样做。

  2. 您可以mock react-mic module。这比 #1 更容易实现,但仍然相当困难。

  3. 您可以在测试中依赖shallow()。所以你根本不需要模拟任何与音频相关的东西。我想建议你这样做。

【讨论】:

  • 太奇怪了,在我的例子中,我从一个文件中测试了一个简单的打字稿函数,开玩笑告诉我一个错误Jest encountered an unexpected token,但是当我删除了一个与axios 相关的api函数并再次测试时。它像平静一样工作。
【解决方案2】:

已经是这样了。开玩笑忽略了node_modules。你看到的只是一个堆栈跟踪。仔细检查您的测试代码,那里发生了错误。

【讨论】:

    【解决方案3】:

    在配置 jest 时尝试使用testPathIgnorePatterns

    "jest": {
        ...
        "testPathIgnorePatterns": [
          "<rootDir>/(build|docs|node_modules)/"
        ]
    

    【讨论】:

    • Krif Create React App 仅支持覆盖这些 Jest 选项: • collectCoverageFrom • coverageReporters • coverageThreshold • snapshotSerializers。
    • 你试过了吗?我看不出为什么 Create React App 会受限于这些选项。
    • create-react-app 限制我们使用此选项
    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 2018-07-06
    • 2017-11-09
    • 2019-08-23
    • 2023-03-26
    • 2019-01-30
    • 1970-01-01
    • 2017-02-09
    相关资源
    最近更新 更多