环境搭建

  1. // 预安装 ts jest(依赖ts)
  2. npm i -g jest typescript ts-jest
  3. // 安装ts-jest 和 类型
  4. npm i -D jest ts-jest @types/jest
  5. // 初始化ts-jest配置 生成jest.config.js
  6. ts-jest config:init
  7. // 修改package.json
  8. "scripts": {
  9. "test": "jest",
  10. "test:watch": "jest --watch",
  11. "test:cov": "jest --coverage",
  12. },
  13. // 指令运行
  14. npm test 测试用例情况
  15. npm run testc 覆盖率情况
  16. // 可以安装VSCode插件 jest runner 点击Run可以快捷调试单文件
  17. // tsconfig.json
  18. "esModuleInterop": true,

jest使用

官网
文档

  1. module.exports = {
  2. "preset": "ts-jest",
  3. "moduleFileExtensions": [
  4. "js",
  5. "json",
  6. "ts"
  7. ],
  8. "rootDir": "src",
  9. "testRegex": ".*\\.spec\\.ts$",
  10. "transform": {
  11. "^.+\\.ts$": "ts-jest"
  12. },
  13. "coverageDirectory": "../coverage",
  14. "testEnvironment": "node"
  15. };
  1. # test
  2. /coverage

示例

  1. export function sum(a: number, b: number) {
  2. if (a > 0) {
  3. return a + b;
  4. } else {
  5. return 100;
  6. }
  7. }
  1. import { sum } from './filter-func';
  2. test('adds 1 + 2 to equal 3', () => {
  3. expect(sum(1, 2)).toBe(3);
  4. });

image.png
覆盖率表示测试的代码覆盖了测试的文件中的方法数,分支数(条件等),所有代码行是否运行等