随着前端的发展,前端设计的领域已经越来越多,也越来越复杂。这就对我们前端工程化能力,提出了更高的要求。 好的前端工程化一般包括三个大的方面:
Node.js
和浏览器中,使异步测试变得简单有趣。也是非常优秀的框架;test('test',() => {
expect("1").toBe("1");
})
1.jest.config.ts
export default {
clearMocks: true, // 是否每次运行清除mock
collectCoverageFrom: ['src/*.{js,ts}', 'src/**/*.{js,ts}'], //覆盖率文件
coverageDirectory: 'coverage', // 生成覆盖率的文件名
coverageProvider: 'v8',
coverageThreshold: { // 覆盖率阈值
global: {
branches: 90,
functions: 95,
lines: 95,
statements: 95,
},
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'json', 'jsx', 'node'], // 文件扩展
preset: 'ts-jest', //ts
setupFilesAfterEnv: [ // 每次test的启动文件,类似main.ts
"/__tests__/boot.ts"
],
testEnvironment: 'jest-environment-jsdom', // js
testRegex: '(/__tests__/.+\\.(test|spec))\\.(ts|tsx|js)$', // 要进行test的文件正则
};
2、package.json 启动配置,
"scripts": {
"test": "jest",
"test:w": "jest --watchAll",
"test:c": "jest --coverage", // 生成覆盖率文件
},
3、运行yarn test :c
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 100 | 89.47 | 100 | 100 |
01demo.js | 100 | 50 | 100 | 100 | 2
03es6.js | 100 | 50 | 100 | 100 | 2
04async.js | 100 | 100 | 100 | 100 |
05hook.js | 100 | 100 | 100 | 100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 6 passed, 6 total
Tests: 28 passed, 28 total
Snapshots: 0 total
Time: 9.378 s, estimated 11 s
Ran all test suites.
✨ Done in 10.55s.
%stmts是语句覆盖率(statement coverage):是不是每个语句都执行了?
%Branch分支覆盖率(branch coverage):是不是每个if代码块都执行了?
%Funcs函数覆盖率(function coverage):是不是每个函数都调用了?
%Lines行覆盖率(line coverage):是不是每一行都执行了?
专业术语里,把describe包含的块叫做suite,把it/test包含的块叫做specification,也简称为spec,在一个suite里面可以包含多个数量的spec,但是也要注意结构化语义化。
代码参考github地址
1、jest单元测试-基础
2、jest单元测试-匹配器
3、jest单元测试-作用域
4、jest单元测试-更多