1、简介
Jest是facebook
出品的JavaScript单元测试软件
最常用的代码: expect(变量).toEqual(期待值)
;
2、格式
describe("number test", ()=>{
it('1 is true', ()=>{
expect(1).toBeTruthy()
})
test('2 is true',()=>{
expect(2).toBeTruthy()
})
})
- describe 描述, decribe会形成一个作用域
- it 断言
- expect 期望
- test 测试,类似it
3、常用断言归纳
普通匹配器
toBe - toBe 使用 Object.is 来测试是否完全相等
.not - 用来测试相反的用例
.toEqual如果你想检查某个对象的值,请改用 toEqual。
toBe
最简单的测试值的方法是看是否精确匹配。
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
toEqual
如果你想检查某个对象的值,请改用 toEqual。
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
.not
用来测试相反的用例
test('null', () => {
const n = null;
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
});
布尔值匹配器
toBeNull 只匹配 null
toBeUndefined 只匹配 undefined
toBeDefined 与 toBeUndefined 相反
toBeTruthy 匹配任何 if 语句为真
toBeFalsy 匹配任何 if 语句为假
test('null', () => {
const n = null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
expect(n).toBeFalsy();
});
test('zero', () => {
const z = 0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
});
数字匹配器
.toBeGreaterThan() - 大于
.toBeGreaterThanOrEqual() 大于等于
.toBeLessThan() - 小于
.toBeLessThanOrEqual() - 小于等于
.toBeCloseTo() - 浮点数比较
字符串匹配器
toMatch - 正则表达式的字符
.toHaveLength(number) - 判断一个有长度的对象的长度
expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);
数组匹配器
.toContain(item) - 判断数组是否包含特定子项
.toContainEqual(item) - 判断数组中是否包含一个特定对象
4、安装运行
安装
npm install -g jest
编写
__test__中的js文件
运行
npm run test || npm test
学习链接:
https://blog.csdn.net/haoaiqian/article/details/90721016
https://blog.csdn.net/peade/article/details/107051177
https://www.jianshu.com/p/2beed3c5317c