断言库chai的用法

工作中经常需要自己写单元测试,而写单元测试除了掌握测试框架,还必须掌握断言库的用法。现就断言库chai的用法作以总结。chai有三种断言风格供我们使用,expectshouldassert。本文只介绍expect风格的断言用法。

  • 综述
    expect断言的写法都是一样的。头部是expect方法,尾部是断言方法,比如equal、a/an、ok、match等。两者之间使用toto.be连接。
  • 关于类型判断
    我们可以对js中各种数据类型进行判断,包括常见的数字,字符串,布尔值,对象,数组,函数及ES6新增的数据类型。
    代码如下:
    expect('foo').to.be.a('string');
    expect(false).to.be.a('boolean');
    expect(12).to.be.a('number');
    expect(null).to.be.a('null');
    expect(undefined).to.be.a('undefined');
    expect({}).to.be.a('object');
    expect([]).to.be.a('array');
    expect(Math.cos).to.be.a('function');
    expect(new Error).to.be.a('error');
    expect(/123/).to.be.a('regexp');
  • 关于严格相等
    对于基本类型的数据,我们使用equal方法来判断是否相等,对于引用类型的数据,我们有两种方法来判断是否相等。一是使用eql来判断是否相等,二是在equal前加上deep即可。
    代码如下:
    expect(1).to.equal(1);
    expect('foo').to.equal('foo');
    expect(true).to.equal(true);
    expect(null).to.equal(null);
    expect(undefined).to.equal(undefined);
    expect({a: 1}).to.eql({a: 1});
    expect([1, 2]).to.eql([1, 2]);
    expect([1, 2]).to.deep.equal([1, 2]);

除此之外,对于一些常见的值,有一些简写的语法。

    expect(false).to.be.false;
    expect(true).to.be.true;
    expect(null).to.be.null;
    expect(undefined).to.be.undefined;
    expect(NaN).to.be.NaN;

不建议使用简写语法。

  • 关于长度
    代码如下:
    expect([1, 2, 3]).to.have.lengthOf(3);
    expect('foo').to.have.lengthOf(3);
    expect([]).to.have.lengthOf(0);
    expect('').to.have.lengthOf(0);

对于长度为0,我们也有简写语法,但不建议使用。

    expect([]).to.be.empty;
    expect('').to.be.empty;
  • 关于包含
    代码如下:
    expect('foobar').to.include('foo');
    expect([1, 2, 3]).to.include(2);
    expect('foobar').to.match(/^foo/);
    expect({a: 1}).to.have.property('a');
    expect({a: 1, b: 2}).to.have.all.keys('a', 'b');
    expect({a: 1, b: 2}).to.have.all.keys(['a', 'b']);
    expect({a: 1, b: 2}).to.have.any.keys('a');

以上就是断言库chai的一些常用方法,还有一些其他的方法,但是官方不建议使用,掌握这些就已经足够我们写单元测试了。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容