zoukankan      html  css  js  c++  java
  • 前端测试框架Jest系列教程 -- Matchers(匹配器)

    写在前面:

      匹配器(Matchers)是Jest中非常重要的一个概念,它可以提供很多种方式来让你去验证你所测试的返回值,本文重点介绍几种常用的Matcher,其他的可以通过官网api文档查看。

    常用的匹配方式:

    第一种:相等匹配,这是我们最常用的匹配规则  

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

    在这段代码中 expact(2 + 2) 将返回我们期望的结果,通常情况下我们只需要调用expect就可以,括号中的可以是一个具有返回值的函数,也可以是表达式。后面的 toBe  就是一个matcher,当Jest运行的时候它会记录所有失败的matcher的详细信息并且输出给用户,让维护者清楚的知道failed的原因,如果我们改成 toBe(5),将会有下面输出:

    这样的输出结果非常易于我们去check错误点。

    toBe 是测试具体的某一个值,如果需要测试对象,需要用到toEqual 

    test('object assignment', () => {
      const data = {one: 1};
      data['two'] = 2;
      expect(data).toEqual({one: 1, two: 2});
    });

    toEqual是通过递归检查对象或数组的每个字段。你也可以自己实现一个来测试:

    test('adding positive numbers is not zero', () => {
      for (let a = 1; a < 10; a++) {
        for (let b = 1; b < 10; b++) {
          expect(a + b).not.toBe(0);
        }
      }
    });

     第二种:真实性匹配,比如:对象是否为null,集合是否为空等等

     在测试中,您有时需要区分undefined、null和false,但有时希望以不同的方式处理这些问题,Jest帮助你明确您想要什么。比如:

    • toBeNull 仅当expect返回对象为 null时
    • toBeUndefined 仅当返回为 undefined
    • toBeDefined 和上面的刚好相反,对象如果有定义时
    • toBeTruthy 匹配任何返回结果为true的
    • toBeFalsy 匹配任何返回结果为false的

    代码示例:

    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;
    test('two plus two', () => {
      const value = 2 + 2;
      expect(value).toBeGreaterThan(3);
      expect(value).toBeGreaterThanOrEqual(3.5);
      expect(value).toBeLessThan(5);
      expect(value).toBeLessThanOrEqual(4.5);
    
      // toBe and toEqual are equivalent for numbers
      expect(value).toBe(4);
      expect(value).toEqual(4);
    });
    
    
    
      expect(z).not.toBeNull();
      expect(z).toBeDefined();
      expect(z).not.toBeUndefined();
      expect(z).not.toBeTruthy();
      expect(z).toBeFalsy();
    });

    自己可以运行一下上面代码就可以知道每一个匹配器具体的规则是什么。选择什么样的规则依赖于你期望的想要验证什么样的结果。

    第三种:数字型匹配

      这种匹配规则非常语义化,不需要解释都能看得懂,示例代码如下:

    test('two plus two', () => {
      const value = 2 + 2;
      expect(value).toBeGreaterThan(3);
      expect(value).toBeGreaterThanOrEqual(3.5);
      expect(value).toBeLessThan(5);
      expect(value).toBeLessThanOrEqual(4.5);
    
      // toBe and toEqual are equivalent for numbers
      expect(value).toBe(4);
      expect(value).toEqual(4);
    });

    需要注意的是对于float类型的浮点数计算的时候,需要使用toBeCloseTo而不是 toEqual ,因为避免细微的四舍五入引起额外的问题。

    test('adding floating point numbers', () => {
      const value = 0.1 + 0.2;
      //expect(value).toBe(0.3);           This won't work because of rounding error
      expect(value).toBeCloseTo(0.3); // This works.
    });

    最开始看这段代码的时候有一点疑惑,为什么0.1 + 0.2 不等于 0.3 ,查阅资料后发现几乎所有的语言中浮点数计算的时候都存在这样的问题

    如果大家有兴趣可以去这里查看:http://u3xyz.com/detail/28 或者更专业的解释:http://0.30000000000000004.com/

     第四种:字符型匹配

    使用 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/);
    });

     第五种:数组类型匹配

    使用 toContain 检查是否包含

    const shoppingList = [
      'diapers',
      'kleenex',
      'trash bags',
      'paper towels',
      'beer',
    ];
    
    test('the shopping list has beer on it', () => {
      expect(shoppingList).toContain('beer');
    }); 

    第六种:异常匹配

    如果想要测试function是否会抛出特定的异常信息,可以用 toThrow 规则

    function compileAndroidCode() {
      throw new ConfigError('you are using the wrong JDK');
    }
    
    test('compiling android goes as expected', () => {
      expect(compileAndroidCode).toThrow();
      expect(compileAndroidCode).toThrow(ConfigError);
    
      // You can also use the exact error message or a regexp
      expect(compileAndroidCode).toThrow('you are using the wrong JDK');
      expect(compileAndroidCode).toThrow(/JDK/);
    });

    写在最后

      本文仅仅只是介绍了几种常用的匹配器,如果想要了解更多可以参考 官方API 文档

          目前的项目中刚开始使用Jest,看到国内关于Jest的中文文档并不是很多,所以就想写一个系列介绍给大家,大部分内容是从官方文档中翻译过来,如果有任何不准确的地方希望大 家能指出来,我将非常及时的更改。

      如果觉得本文对您有用,麻烦动动手指推荐一下,谢谢。

          下一节内容将介绍:Jest如何测试异步代码,敬请期待

    系列教程:

       1. 前端测试框架Jest系列教程 -- Matchers(匹配器)

       2.前端测试框架Jest系列教程 -- Asynchronous(测试异步代码)

       3.前端测试框架Jest系列教程 -- Mock Functions(模拟器)

       4.前端测试框架Jest系列教程 -- Global Functions(全局函数)

  • 相关阅读:
    JavaScript完整总结
    vue引入iframe的父子页面的数据传递
    随笔开发中笔记
    关于表格(table)的操作
    es6--6.字符串相关
    ES6--5.数组4个新增方法
    ES6--4.解构赋值
    sublime 远程连接服务器编辑
    ajaxSubmit
    修改 debian 时区
  • 原文地址:https://www.cnblogs.com/Wolfmanlq/p/8018370.html
Copyright © 2011-2022 走看看