jest 安装
中文官网: 快速开始 · Jest
1. 安装命令行
npm install --save-dev jest
2. package.json 中配置
{
"scripts": {
"test": "jest"
}
}
3. 运行 yarn test 或者 npm run tst
4. 测试文件后缀需要为 .spec.js 或者 .test.js
5. 需要有两个必会的方法
-
test :Jest封装的测试方法,一般填写两个参数,描述和测试方法
-
expect :预期方法,就是你调用了什么方法,传递了什么参数,得到的预期是什么
基础匹配器
toBe() | 绝对相等(===) |
toEqual() | 简单类型绝对匹配;复杂类型内容结果的匹配 |
toBeNull() | 匹配 null |
toBeUndefined() | 匹配 undefined |
toBeDefined() | 匹配非 undefined |
toBeTruthy() | 匹配转化后为 true |
toBeFalsy() | 匹配转化后为 false |
toBeGreaterThan() | 相当于大于号 |
toBeLessThan() | 相当于小于号 |
toBeGreaterThanOrEqual() | 相当于大于等于号 |
toBeLessThanOrEqual() | 相当于大于等于号 |
toBeCloseTo() | 解决js浮点错误 |
toMatch(regExp/string) | 用正则表达式或者字符串匹配字符串片段 |
toContain() | 匹配数组或者Set中的某一项 |
toThrow() | 匹配异常处理,如果抛出了异常就过测试用例 |
expect({a:1}).toBe({a:1})//判断两个对象是否相等
expect(1).not.toBe(2)//判断不等
expect(n).toBeNull(); //判断是否为null
expect(n).toBeUndefined(); //判断是否为undefined
expect(n).toBeDefined(); //判断结果与toBeUndefined相反
expect(n).toBeTruthy(); //判断结果为true
expect(n).toBeFalsy(); //判断结果为false
expect(value).toBeGreaterThan(3); //大于3
expect(value).toBeGreaterThanOrEqual(3.5); //大于等于3.5
expect(value).toBeLessThan(5); //小于5
expect(value).toBeLessThanOrEqual(4.5); //小于等于4.5
expect(value).toBeCloseTo(0.3); // 浮点数判断相等
expect('Christoph').toMatch(/stop/); //正则表达式判断
expect(['one','two']).toContain('one'); //匹配数组
function compileAndroidCode() {
throw new ConfigError('you are using the wrong JDK');
}
test('compiling android goes as expected', () => {
expect(compileAndroidCode).toThrow();
expect(compileAndroidCode).toThrow(ConfigError); //判断抛出异常
})
项目中使用
基础使用
1. 再需要测试的文件同级位置创建与测试文件名称一致的 .spec.js 文件 或者 .test.js 文件
2. 引入对应文件,并使用 describe 和 test 或者 it 进行单元测试
import MyApp from './my-app.vue'
describe('myApp test', () => {
it('two plus two is four', () => {
expect(2 + 2).toBe(4);
})
// or
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
})