# 单元测试 - jest

Jest (opens new window) 是由 Facebook 开源出来一个测试框架,它集成了断言库、mock、快照测试、覆盖率报告等功能。

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.
It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!

# 安装

安装依赖

yarn add jest -D
npm i jest -D
1
2

添加运行脚本,在 `package.json`` 中添加:

{
  "scripts": {
    "test": "jest",
    "test:coverage": "jest --coverage"
  } 
}
1
2
3
4
5
6

使用 babel ,现在肯定都会在项目中使用 es6 及之后的新语法特性,当前 node 版本不支持,所以需要转义。

yarn add --dev babel-jest @babel/core @babel/preset-env
1

jest 默认使用 babel-jest (安装后)进行代码转义,如果要添加额外的预处理器,则需要在 jest 配置文件里面显式的定义 babel-jest 作为 js 文件的处理器(因为一旦添加了 transform 配置,就不会自动使用 babel-jest)。比如配置 vue-jest 处理 vue 文件的时候。

// jest.config.js
module.exports = {
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  }
}
1
2
3
4
5
6
7

同时记得修改 .babelrc 配置,加上 test 环境的配置:

{
  "env": {
      "test": {
        "presets": [
          ["@babel/preset-env", { "targets": { "node": "current" } }]
        ]
      }
    }
}
1
2
3
4
5
6
7
8
9

# 配置

jest 添加的配置,可以放在 package.jsonjest key 下面,也可以放在根目录的 jest.config.js

// jest.config.js
module.exports = {
  testMatch: [ '**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)' ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
  moduleFileExtensions: ["js", "json", "vue"],
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  transformIgnorePatterns: [ // 预处理忽略的文件
    '/node_modules/(?!test-component).+\\.js$',
  ],
  collectCoverage: true, // 是否统计覆盖率信息
  collectCoverageFrom: [ // 数组,覆盖率统计的文件范围。
    '**/src/util/*.{ts,js}',
  ],
  coverageReporters: [ // 覆盖率报告类型
    'text',
    'json',
    'lcov',
    'cobertura',
  ],
  reporters: ['jest-junit'] // 生成测试报告
}
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

# rootDir

默认值:是 jest 配置文件或者 package.json 所在目录,都没有的话用 pwd。 主要用来在其它配置中定位路径。

# testMatch

默认值: [ '**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)' ] 测试代码可以写在 __test__ 文件夹下,也可以和源文件放在一起,同名,但是后缀名 .test.js 或者 .spec.js。也可以自定义配置:

# moduleNameMapper

定义别名,类似 webpack 的 alias。可以使用 rootDir

# moduleFileExtensions

默认值:["js", "json", "jsx", "ts", "tsx", "node"] 测试文件的类型。

# transform

默认值:{"^.+\\.[jt]sx?$": "babel-jest"} 配置预处理器,比如处理 es6 语法,vue 文件等。

# 匹配器

匹配器用来实现断言功能。

test('Adding 1 + 1 equals 2', () => {
  expect(sum(1, 1)).toBe(2)
})
1
2
3

# 参考

上次更新: 7/14/2021, 11:19:16 AM