JEST
一、安装
jest用于进行js代码测试的工具
1、安装
安装命令:cnpm install --save-dev jest
2、入门使用
简单使用案例
function sum(a, b) {
return a + b;
}
module.exports = sum;
// 创建一个需要测试的文件
编写测试用例
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
然后在package.json
里面添加命令,如:
{
"scripts": {
"test": "jest"
}
}
最后,运行 yarn test
或 npm run test
此时就可以看到控制台打印提升,判断测试结果
或者使用npx jest
,直接调用jest
命令
3、jest配置
运行命令 npx jest --init
,进入命令配置过程
选择需要的配置,然后就会生成jest.config.js文件,也可以在里面修改配置
4、jest覆盖率
如果配置了覆盖率,即coverageDirectory: "导出文件名",
使用命令:npx jest --coverage
,
- 输入命令执行后会打印项目的测试覆盖率
- 同时生成
lcov-report
文件,里面的index.html文件就是测试报告
5、文件watch
执行命令:npx jest --watchAll
,或者添加到packjson里面。
二、开始使用
1、基础语法
1、期望器:
expect
:期望器
如expect(2 + 2)
,我们期望运行2 + 2
这个逻辑
2、匹配器:
toBe
:===
如:toBe(4)
,我们用来匹配期望器运行的值是否匹配
案例:
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
// 测试2+2 ?= 4
});
not.toBe
:取反匹配器,就是取非的意思toEqual
:对象值匹配器
对象的值需要专门的匹配器:如
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
toBeNull
只匹配null
toBeUndefined
只匹配undefined
toBeDefined
与toBeUndefined
相反toBeTruthy
匹配任何if
语句为真toBeFalsy
匹配任何if
语句为假toBeCloseTo
匹配浮点数的相等,如(0.1 + 0.2)与0.3进行比较使用这个匹配器。toBeGreaterThen
:大于逻辑—>
toBeGreaterThenOrEqual
:大于等于—>=
toBeLessThen
:小于逻辑 —<
toBeLessThenOrEqual
:小于等于—<=
toMatch
:匹配字符串中是否含有
使用案例
test('toMatch匹配器', () => {
const src = '旭大王,旭宝宝';
expect(src).toMatch('旭大王');
})
toContain
:数组匹配器,和上面的字符串匹配器同理toThrow
:异常匹配器,如new Error
创造的异常
2、jest支持es6
jest是不支持es6语法的,所以需要使用babel处理
需要插件:@babel/core
,@babel/preset-env
然后在项目根目录下创建babel的配置文件:.babelrc
{
"presets": [
[
"@babel/preset-env", {
"target": {
"node": "current"
}
}
]
]
}
或着配置为
{
"env": {
"test": {
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
}
}
3、异步代码测试
1、promise一型
异步代码
import axios from 'axios';
export const fetchData = (callback) => {
axios.get('地址').then((res) => {
callback(res);
});
};
测试用例test
import { fetchData } from './fetchData.js';
test('异步测试1', (done) => {
fetchData((data) => {
expect(data).toEqual({
success: true
});
// 这里有坑,不加done,无法监视返回后的结果
// 想要测试返回接口,等待异步操作完成,必须加done()
done();
});
});
2、promise二型
异步代码
import axios from 'axios';
export const fetchData = (url) => {
return axios.get(url);
};
测试用例test
import { fetchData } from './fetchData.js';
test('异步测试2', () => {
// return 和上面的 done 作用是一样的。
return fetchData('地址').then((response) => {
expect(response?.data).toEqual({
success: true
});
});
});
3、测试返回404
import { fetchData } from './fetchData.js';
test('异步测试2', () => {
// 测试断言,无论出不出现错误,都要执行测试用例(1)次
expect.assertions(1);
return fetchData('地址').catch((error) => {
// 通过捕获错误检测是否含有404检测错误。
expect(error.toString().indexOf(404) > -1).toBe(true);
});
});
4、async类型
import { fetchData } from './fetchData.js';
test('异步测试2', async() => {
const responese = await fetchData('地址');
expect(response?.data).toEqual({
success: true
});
});
4、jest的hook
- 所有测试执行前:
beforAll
,
beforeAll(() => {
console.log('所有测试用例执行前钩子');
})
- 所有测试用例执行后:
afterAll
- 单个测试用例执行前:
beforeEach
- 单个测试用例执行后:
afterEach
beforEach(() => {
console.log('测试用例执行前');
})
test('测试用例构造', () => {
expect(0.2 + 0.1).toBeCloseTo(0.3);
})
afterEach(() => {
console.log('测试用例执行后');
})
5、测试分组
通一文件对多个测试进行分组
分组:describe
describe('分组1', () => {
test('测试1组a', () => { });
test('测试1组b', () => { });
});
describe('分组2', () => {
test('测试2组a', () => { });
test('测试2组b', () => { });
})
6、hook的作用域
上面介绍了分组,每个组都可以有自己的前置和后置钩子。
规则:
- 父级的钩子可以继承给子级,在子级内部执行
- 子级内部自己的钩子也执行,与外部继承的互不干扰
- 先执行外部继承的钩子,在执行内部的钩子。
7、识别webpack别名
正常来说,jest是无法识别webpack配置的路径别名
// 在jest.config.js里面进行配置
module.exports = {
moduleNameMapper: {
'@/(.*)$': '<rootDir>/src/$1.js',
}
}