在我们使用mocha进行测试的时候,会结合断言库去使用,经常一起使用的是chai,但是还有assert,expect,should这几种断言库,那么接下来了解一下他们的区别
assert
TDD风格
API样例:
assert("mike" == user.name);
should
BDD风格
API样例:
foo.should.be("aa");
expect
BDD风格,基于should的简化
API样例:
expect(foo).to.be("aa");
chai
BDD/TDD风格,同时支持should,assert,expect
API样例:
foo.should.be("aa");
assert("mike" == user.name);
expect(foo).to.be("aa");
should和expect的区别
当被测对象为undefined时,should就失效,而expect依然可以给出信息
例如使用should:
// foo === undefined
foo.should.equal('aa');
此时错误信息为: Cannot read property 'should' of undefined,如果使用expect:
// foo === undefined
expect(foo).to.equal('aa');
给出的信息为:expected undefined to equal 'foo'
故使用expect优于should