• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
小码哥-倩倩
博客园    首页    新随笔    联系   管理    订阅  订阅

(四)Jest匹配器

学习jest匹配器之前先要修改配置文件,打开package.json文件:

  "scripts": { 
    "test": "jest --watchAll",
    "coverage": "jest --coverage"
  },

让Jest监听所有测试(test.js)文件的变化,如果有变化就自动跑测试用例。

一、比较结果匹配器

1> toBe

test('测试加法 3+7', () => {
  toBe为匹配器 matchers
   expect(10).toBe(10);
  //toBe相当于js中的 object.is ===
});
2> toEqual

test('测试加法 3+7', () => {

   //toEqual为匹配器

   const a = { one : 1 };

   expect(a).toEqual({ one : 1 });

});

3> toBeNull

test('测试加法 3+7', () => {

  const a = null;

  expect(a).toBeNull();

});

二、真假有关的匹配器

1> toBeUndefined

2> toBeDEfined

3> toBeTruthy

4> toBeFalsy

三、数字相关匹配器

1> toBeGreaterThan

    test('toBeGreaterThan', () => {

  const count = 10;

  expect(count).toBeGreaterThan(3);

    });

2> toBeLessThan

    test('toBeLessThan', () => {

  const count = 10;

  expect(count).toBeLessThan(13);

   });

3> toBeGreaterThanOrEqual

test('toBeGreaterThanOrEqual',()=>{
const a= 5
expect(a).toBeGreaterThanOrEqual(5)
})

4> toBeCloseTo  主要用于带有浮点小数时使用

test('toBeCloseTo',()=>{
const a= 5.1
expect(a).toBeCloseTo(5.1)
})

四、String匹配器

1> toMatch

test('toMatch', () => { 
  const str = 'http://www.dell-lee.com';
  expect(str).toMatch(/dell-lee/);
});

2> toContain  主要用于数组

 test('toContain', () => {

  const arr = ['dell','lee','imooc'];

  const data = new Set(arr);

   expect(data).toContain('dell');

 });

3> toThrow 抛出异常

 const throwNewErrorFunc = () => {
  throw new Error('this is a new error');
 }
   test('toThrow', () => {
  // expect(throwNewErrorFunc).not.toThrow('this is a new error');
  expect(throwNewErrorFunc).not.toThrow(/this is a new error/);
   });
   //两处的error信息要一致,否则报错


posted @ 2020-04-29 08:59  小码哥-倩倩  阅读(378)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3