只需在根目录下安装 jest 包。然后,在jest.config.js文件中添加projects [array<string | ProjectConfig>]
配置:
Jest 将同时在所有指定项目中运行测试。这对于 monorepos 或同时处理多个项目时非常有用。
我的项目使用lerna 来管理单声道存储库。
文件夹结构:
⚡ tree -L 2 -I 'node_modules|examples'
.
├── LICENSE
├── coverage
│ ├── clover.xml
│ ├── coverage-final.json
│ ├── lcov-report
│ └── lcov.info
├── jest.config.js
├── jest.setup.js
├── lerna.json
├── package-lock.json
├── package.json
├── packages
│ ├── redux-saga-examples
│ └── redux-toolkit-example
└── tsconfig.json
5 directories, 10 files
有两个包:redux-saga-examples 和 redux-toolkit-example。这些包中有很多测试文件。
根中的package.json:
{
"name": "root",
"private": true,
"scripts": {
"bootstrap": "lerna bootstrap",
"clean": "lerna clean",
"test": "jest"
},
"devDependencies": {
"@types/jest": "^26.0.24",
"lerna": "^4.0.0",
"jest": "^27.0.6",
"ts-jest": "^27.0.4",
"ts-node": "^9.1.1",
"typescript": "^4.3.5",
"prettier": "^2.3.1"
},
"dependencies": {
"axios": "^0.21.4"
}
}
jest.config.js:
const reduxSagaExamplesPkg = require('./packages/redux-saga-examples/package.json');
const RTKExamplesPkg = require('./packages/redux-toolkit-example/package.json');
module.exports = {
verbose: true,
projects: [
{
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['./jest.setup.js'],
displayName: reduxSagaExamplesPkg.name,
testMatch: ['<rootDir>/packages/redux-saga-examples/**/?(*.)+(spec|test).[jt]s?(x)'],
},
{
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['./jest.setup.js'],
displayName: RTKExamplesPkg.name,
testMatch: ['<rootDir>/packages/redux-toolkit-example/**/?(*.)+(spec|test).[jt]s?(x)'],
},
],
};
现在,您可以在项目根目录下运行npm t npm 脚本来运行所有测试。