Jest 入门(二),常用expect方法

博客介绍了Jest的基础语法,返回的‘expectation’对象与matcher会被Jest比较并输出测试结果,还可调用被测function。同时阐述了Jest在比较null、undefined、true、false、number、string、Arrays等方面的情况,更多expect用法可查询官方文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.基础语法

test('two plus two is four', () => {
  expect(2 + 2).toBe(4);
});

expect()返回被称作“expectation”的对象。toBe()被称作matcher。Jest会对两者进行比较并输出测试结果。

相应的,expect()toBe()还可以调用被测的function

test('two plus two is four', () => {
  const add = 2+2;
  const value =4;
  expect(add).toBe(value);
});

还可以用not.toBe():

expect(add).not.toBe(value);

2.比较null,undefined,true,false

 expect(n).toBeNull(); // 比较是否为null
 expect(n).toBeDefined(); // 比较是否为defined
 expect(n).not.toBeUndefined(); // 比较是否为undefined
 expect(n).not.toBeTruthy(); // 比较是否为true
 expect(n).toBeFalsy(); // 比较是否为false

3.比较number

 expect(value).toBe(4); 
 expect(value).toEqual(4);

对于number,toBe()和toEqual()两者在大部分时候都是等价的

4.比较string

使用toMatch()方法

test('there is no I in team', () => {
  expect('team').not.toMatch(/I/);
});

test('but there is a "stop" in Christoph', () => {
  expect('Christoph').toMatch(/stop/);
});

5.比较Arrays

使用toContain()方法

const shoppingList = [
  'diapers',
  'kleenex',
  'trash bags',
  'paper towels',
  'beer',
];

test('the shopping list', () => {
  expect(shoppingList).toContain('beer');
  expect(shoppingList).not.toContain('pork');
});

6.更多expect用法

请查询Jest官方文档,链接官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值