在create-react-app中运行`npm test`时如何忽略某些文件?

CKA*_*CKA 10 unit-testing npm reactjs create-react-app

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

 "jest": {
        "collectCoverageFrom": [
            "src/App.test.js"
        ]
    },
Run Code Online (Sandbox Code Playgroud)

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

tob*_*ias 21

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

"jest": {
  "collectCoverageFrom": [],
  "coverageThreshold": {},
  "coverageReporters": [],
  "snapshotSerializers": []
}
Run Code Online (Sandbox Code Playgroud)

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

解决方案1

弹出创建 React App 并使用testPathIgnorePatterns.

解决方案2

您仍然可以通过将--testPathIgnorePatterns选项传递给react-scripts test.

例如:

"test": "react-scripts test --testPathIgnorePatterns=src/ignoredDirectory --env=jsdom"
Run Code Online (Sandbox Code Playgroud)

  • 请注意,使用“testPathIgnorePatterns”作为 cli 参数会破坏使用“npm test Testname”或“npm test -- -t TestName”运行一个测试的能力。 (2认同)

bad*_*tax 7

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

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

例如:

如果我的 中设置了以下内容package.json

"test": "react-scripts test --testPathIgnorePatterns=e2e",
Run Code Online (Sandbox Code Playgroud)

然后运行:npm test MyTest

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

玩笑将被忽略e2eApp

我发现的解决方法是不使用testPathIgnorePatternscli arg,而是使用testMatchjest 配置。

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

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

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

"testMatch": [
  "<rootDir>/src/modules/**/__tests__/**/*.{js,jsx,ts,tsx}",
  "<rootDir>/src/modules/**/*.{spec,test}.{js,jsx,ts,tsx}"
]
Run Code Online (Sandbox Code Playgroud)

  • 根据https://create-react-app.dev/docs/running-tests/#configuration,“testPathIgnorePatterns”在“package.json”中不可配置 (6认同)