node基础学习--单元测试jest

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值