一、Jest 简介
优势: 速度快、API简单、配置简单
前置: Jest 不支持 ES Module 语法,需要安装 babel
npm install -D @babel/core @babel/preset-env
.babelrc
{
"presets": [
[
"@babel/preset-env", {
"targets": {
"node": "current"
}
}
]
]
}
jest 在运行前会检查是否安装 babel,如果安装了会去取 .babelrc 文件,结合 babel 将代码进行转化,运行转化后的代码。 3. jest 默认配置
npx jest --initjest 模式
jest --watchAll:当发现测试文件变动,将所有测试文件重新跑一遍
jest --watch:需要和 git 结合使用,会比较现有文件和 commit 的文件的差异,只测试差异文件
二、Jest 匹配器
常见匹配器
toBe
toEqual:判断对象内容是否相等
toMatchObject:expect(obj).toMatchObject(o),期望 o 中包含 obj
toBeNull
toBeUndefined
toBeDefinded
toBeTruthy
toBeFalsy
not:用于否定,比如 .not.toBeTruthy()
Number 相关
toBeGreaterThan(大于) / toBeGreaterThanOrEqual(大于等于)
toBeCloseTo:用于比较浮点数,近似相等时断言成立
toBeLessThan / toBeLessThanOrEqual
String 相关
toMatch:参数可以传字符串或正则
Array Set 相关
toContain
异常匹配器
toThrow:
const throwError = () => {
throw new Error('error')
}
it('can throw error', () => {
expect(throwError).toThrow('error') // 判断throw函数可以抛出异常,异常信息为 "error"。也可以写正则
})
这里有个小技巧:当我们想忽略掉单个文件中的其他测试用例,只针对一个测试用例做调试的时候,可以加上 .only
it.only('test', () => {
// ...
})
但这并不会忽略其他测试文件的测试用例
三、测试异步代码
import axios from 'axios'
export function getData1() {
return axios.get('http://www.dell-lee.com/react/api/demo.json')
}
export function getData2(fn) {
axios.get('http://www.dell-lee.com/react/api/demo.json').then(res => {
fn(res)
})
}
export function get404() {
return axios.get('http://www.dell-lee.com/react/api/404.json')
}
对于异步代码测试,时机很重要,必须保证我们的测试用例在异步代码走完之后才结束。有以下几种办法:
done,控制测试用例结束的时机
如果函数执行的返回值是 Promise,将这个 Promise return 出去
async + await
import {getData1, getData2, get404} from ‘./fetchData/fetchData’
it(‘getData1 方法1’, (done) => {
getData