单元测试Jest
TIP
开发中,单元测试少不了
依赖
下载jest
yarn add jest --dev
安装后再项目终端输入npx jest --init
会让你选择一些自己的配置
npx jest --init
完事后项目会多一个jest.config.js
的文件,和你的package script
中会多一条jest
的指令
// package.json
{
"scripts": {
"test": "jest",
},
}
匹配器
TIP
以下会罗列出比较常用的匹配器
普通
toBe:object.is 相当于 ===
test('测试加法 3 + 7', () => {
expect(3 + 7).toBe(10)
})
toEqual:内容相等,匹配内容,不匹配引用
test('toEqual 匹配器', () => {
// toEqual 匹配器 匹配对象
const a = { one: 1 }
expect(a).toEqual({ one: 1 })
})
与真假有关的匹配器
toBeNull:只匹配 Null
test('toBeNull 匹配器', () => {
const test = null
expect(test).toBeNull()
})
toBeUndefined:只匹配 undefined
test('toBeUndefined 匹配器', () => {
const test = undefined
expect(test).toBeUndefined()
})
toBeDefined: 与 toBeUndefined 相反,这里匹配 null 是通过的
test('toBeDefined 匹配器', () => {
const test = null
expect(test).toBeDefined()
})
toBeTruthy:匹配任何 if 语句为 true
test('toBeTruthy 匹配器', () => {
const test = 1
expect(test).toBeTruthy()
})
toBeFalsy:匹配任何 if 语句为 false
test('toBeFalsy 匹配器', () => {
const test = 0
expect(test).toBeFalsy()
})
not:取反
test('not 匹配器', () => {
const test = 1
// 以下两个匹配器是一样的
expect(test).not.toBeFalsy()
expect(test).toBeTruthy()
})
数字
toBeGreaterThan:大于
test('toBeGreaterThan', () => {
const count = 10
expect(count).toBeGreaterThan(9)
})
toBeLessThan:小于
test('toBeLessThan', () => {
const count = 10
expect(count).toBeLessThan(12)
})
toBeGreaterThanOrEqual:大于等于
toBeLessThanOrEqual:小于等于
toBeCloseTo:计算浮点数
toMatch: 匹配某个特定项字符串,支持正则
test('toMatch', () => {
const test = 'http://www.baidu.com'
expect(test).toMatch('baidu')
expect(test).toMatch(/baidu/)
})
数组
toContain:匹配是否包含某个特定项
test('toContain', () => {
//.toContain(item)
const arr = ['a', 'b', 'c']
expect(arr).toContain('a')
})
toContainEqual:匹配是否包含某个对象
test('toContainEqual', () => {
//.toContainEqual(item)
const arr = [{name: 'a'}, {name: 'b'}, {name: 'c'}]
expect(arr).toContainEqual({name: 'a'})
})
异常
toThrow
const throwErrorFn = () => {
throw new Error('error')
}
test('toThrow', () => {
expect(throwErrorFn).toThrow('error')
})
toThrowError
const throwErrorFn = () => {
throw new Error('error')
}
test('toThrowError', () => {
expect(() => throwErrorFn()).toThrowError('error')
})
案例
TIP
再当前目录创建tests文件夹, 测试文件以.test.js
或者.spec.js
,例如:types.spec.js
...
这个时候基本jest
配置就搭建完毕了,可以编写你的单元测试了。
这个时候写个单元测试如下(测试输出是否正确):
//logger.spec.js
import { success, info, error, warning } from '../src/utils/logger';
describe('logger module', () => {
it('logger', () => {
success('成功');
info('信息');
warning('警告');
expect(() => error('错误')).toThrowError("错误");
})
})
会输入如下:
WARNING
运行测试,会报错,因为 Jest 是在 Node 环境中运行的,这种 import ES6 的导入 Node 还不支持,它只支持 commonJS 的导入方法
**解决方案:**下载babel插件转译
npm install @babel/core @babel/preset-env @babel/plugin-transform-modules-commonjs -D
然后再根目录创建.babelrc如下:
{
"env": {
"test": {
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
}
}
再尝试下: 成功了
给个错误的示例:
import { isString, isBoolean, isNumber, isObject, isHtmlElement, isFunction, isUndefined, isDefined } from '../src/utils/types';
describe('data type verify', () => {
it('isString', () => {
const test1 = 'isString';
const test2 = 123;
expect(isString(test1)).not.toBeTruthy(); // isString(test1) 期望应该是输出true 咱们这边故意给加了个not 然后就会报错提示了
expect(isString(test2)).toBeFalsy();
})
})
输出:
会提示尼那块写的有问题,需要改正。
怎么测试html呢? 写个小例子:
import { isString, isBoolean, isNumber, isObject, isHtmlElement, isFunction, isUndefined, isDefined } from '../src/utils/types';
describe('data type verify', () => {
it('isHtmlElement', () => {
const htmlElement = `
<div id='test'>我是 html</div>
`;
document.body.innerHTML = htmlElement;
const test1 = document.getElementById('test');
const test2 = 123;
expect(isHtmlElement(test1)).toBeTruthy();
expect(isHtmlElement(test2)).not.toBeTruthy();
})
})
输出:
修复方法: 再jest.config.js
设置testEnvironment
为jsdom
即可。
jest.config
TIP
jest.config.js
参数稍微介绍下(其他请参考官网配置:https://jestjs.io/zh-Hans/docs/configuration);
module.exports = {
collectCoverage: true, // 覆盖范围监控
coverageReporters: [ // html得形式
'html',
],
testEnvironment: 'jsdom', // 支持jsdom
};