【问题标题】:How to ignore certain files when running `npm test` in create-react-app?在 create-react-app 中运行“npm test”时如何忽略某些文件?
【发布时间】:2019-09-02 02:24:15
【问题描述】:

目前npm test 正在运行所有具有.test.js 扩展名的文件。我想忽略一些文件。我在哪里配置该选项?我试过了

 "jest": {
        "collectCoverageFrom": [
            "src/App.test.js"
        ]
    },

在 package.json 中。 我看不出有什么不同。

【问题讨论】:

标签: reactjs unit-testing npm create-react-app


【解决方案1】:

您可能很想使用 testPathIgnorePatterns 作为 cli 参数,但请注意这会导致意外的副作用,因为它会破坏使用 npm test TestNamenpm test -- -t TestName 运行单个测试的能力。

这是因为,据我所知,testPathIgnorePatterns 非常贪婪,因为testPathIgnorePatterns 参数之后的任何参数都将用作testPathIgnorePatterns 的值。

例如:

如果我的package.json 中有以下设置:

"test": "react-scripts test --testPathIgnorePatterns=e2e",

然后运行:npm test MyTest

那么生成的命令是:react-scripts test --testPathIgnorePatterns=e2e "App"

开玩笑将被忽略e2eApp

我发现的一种解决方法是不使用testPathIgnorePatterns cli arg,而是使用testMatch jest 配置。

假设我想忽略 e2e 目录中的所有文件,那么我可以使用以下正则表达式:

"testMatch": [
  "<rootDir>/src/(?!e2e)*/**/__tests__/**/*.{js,jsx,ts,tsx}",
  "<rootDir>/src/(?!e2e)*/**/*.{spec,test}.{js,jsx,ts,tsx}"
]

或者如果我只想在某个目录中包含测试,我可以使用:

"testMatch": [
  "<rootDir>/src/modules/**/__tests__/**/*.{js,jsx,ts,tsx}",
  "<rootDir>/src/modules/**/*.{spec,test}.{js,jsx,ts,tsx}"
]

【讨论】:

    【解决方案2】:

    Create React App 只允许您在 package.json 中覆盖以下 Jest 配置:

    "jest": {
      "collectCoverageFrom": [],
      "coverageThreshold": {},
      "coverageReporters": [],
      "snapshotSerializers": []
    }
    

    您可以在此处找到覆盖选项的完整列表:https://facebook.github.io/create-react-app/docs/running-tests#configuration

    解决方案 1

    Eject Create React App 并使用testPathIgnorePatterns进行配置。

    解决方案 2

    您仍然可以通过将--testPathIgnorePatterns 选项传递给react-scripts test 来覆盖Jest 的配置。

    例如:

    "test": "react-scripts test --testPathIgnorePatterns=src/ignoredDirectory --env=jsdom"
    

    【讨论】:

    • 如果我只想对特定目录中的文件运行测试怎么办?
    • "test": "react-scripts test --env=jsdom --testMatch=src/App.test.js"。我试过这个,所以只有 App.test.js 运行。但是 npm test 给出了 0 个匹配项。 @tobias
    • 看看这个答案:stackoverflow.com/questions/44446626/… 这可能会有所帮助:)
    • 请注意,使用 testPathIgnorePatterns 作为 cli 参数会破坏使用 npm test Testnamenpm test -- -t TestName 运行一个测试的能力。
    猜你喜欢
    • 2019-07-22
    • 2020-12-09
    • 2020-11-17
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 2018-03-08
    • 2012-06-08
    • 2020-09-23
    相关资源
    最近更新 更多