代码仓库初始化模板 (6) -- Jest

目录

Jest 简单 Javascript 测试框架。

安装

1
npm install --save-dev jest ts-jest @types/jest jest-extended jest-html-reporters eslint-plugin-jest jsonc-parser cross-env

配置

jest.config.ts

jest.config.tsview raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { pathsToModuleNameMapper, JestConfigWithTsJest } from 'ts-jest';
import packageJson from './package.json';
import { Config } from '@jest/types';
import fs from 'node:fs';
import path from 'node:path';
import { parse as jsoncParse } from 'jsonc-parser';

// 默认配置
// import { defaults as tsjPreset } from 'ts-jest/presets'
// import { defaultsESM as tsjPreset } from 'ts-jest/presets';
// import { jsWithTs as tsjPreset } from 'ts-jest/presets';
// import { jsWithTsESM as tsjPreset } from 'ts-jest/presets';
// import { jsWithBabel as tsjPreset } from 'ts-jest/presets';
// import { jsWithBabelESM as tsjPreset } from 'ts-jest/presets';

const displayName: Config.DisplayName = {
name: packageJson.name,
color: 'blue',
};

function getTsconfig() {
const tsconfigFilePath = path.resolve(process.cwd(), './tsconfig.json');
const str = fs.readFileSync(tsconfigFilePath).toString();
return jsoncParse(str);
}

export default async (): Promise<JestConfigWithTsJest> => {
const tsconfig = getTsconfig();
let result: Record<string, any> = {
preset: 'ts-jest',

// Paths mapping
roots: ['<rootDir>'],
modulePaths: [tsconfig.compilerOptions.baseUrl],
moduleNameMapper: pathsToModuleNameMapper(tsconfig.compilerOptions.paths /* { prefix: '<rootDir>/' } */),

setupFilesAfterEnv: ['jest-extended/all'],

displayName,
maxConcurrency: 100,

modulePathIgnorePatterns: ['<rootDir>/dist/'],
};
if (process.env['SHOW_REPORTS'] === 'Y') {
result = {
...result,
collectCoverage: true,
collectCoverageFrom: ['src/**/*.{js,ts}'],
coverageDirectory: './.test-report/coverage-report',
reporters: [
'default',
[
'jest-html-reporters',
{
publicPath: './.test-report/html-report',
filename: 'report.html',
pageTitle: displayName.name,
openReport: true,
enableMergeData: true,
urlForTestFiles: ' ',
},
],
],
};
}
return result;
};

package.json

1
2
3
4
5
6
{
"scripts": {
"test": "cross-env SHOW_REPORTS=Y jest",
"test:watch": "jest --watch"
}
}

ESLint

1
2
3
4
5
6
7
module.exports = {
extends: ['plugin:jest/recommended'],
plugins: ['jest'],
env: {
'jest/globals': true,
}
}

global.d.ts

1
import 'jest-extended';

tsconfig.json

1
2
3
{
"include": ["jest.config.ts", "global.d.ts"]
}