工作中經常需要自己寫單元測試,而寫單元測試除了掌握測試框架,還必須掌握斷言庫的用法。現就斷言庫chai的用法作以總結。chai有三種斷言風格供我們使用,expect
,should
,assert
。本文只介紹expect
風格的斷言用法。
- 綜述
expect
斷言的寫法都是一樣的。頭部是expect
方法,尾部是斷言方法,比如equal、a/an、ok、match
等。兩者之間使用to
或to.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
的一些常用方法,還有一些其他的方法,但是官方不建議使用,掌握這些就已經足夠我們寫單元測試了。