Chai.js断言库API中文文档
基于chai.js官方API文档翻译。仅列出BDD风格的expect/should API。TDD风格的Assert API由于不打算使用,暂时不放,后续可能会更新。
BDD
expect和should是BDD风格的,二者使用相同的链式语言来组织断言,但不同在于他们初始化断言的方式:expect使用构造函数来创建断言对象实例,而should通过为Object.prototype新增方法来实现断言(所以should不支持IE);expect直接指向chai.expect,而should则是chai.should()。
个人比较建议使用expect,should不仅不兼容IE,在某些情况下还需要改变断言方式来填坑。详细的比较可以看看官网Assertion Styles,说的很清楚。
var chai = require('chai') , expect = chai.expect , should = chai.should()
语言链
下面的接口是单纯作为语言链提供以期提高断言的可读性。除非被插件改写否则它们一般不提供测试功能。
.not
对之后的断言取反
expect(foo).to.not.equal('bar')expect(goodFn).to.not.throw(Error)expect({ foo: 'baz'}).to.have.property('foo') .and.not.equal('bar')
.deep
设置deep标记,然后使用equal和property断言。该标记可以让其后的断言不是比较对象本身,而是递归比较对象的键值对
expect(foo).to.deep.equal({ bar: 'baz'})expect({ foo: { bar: { baz: 'quux'}}}) .to.have.deep.property('foo.bar.baz', 'quux')
deep.property中的特殊符号可以使用双反斜杠进行转义(第一个反斜杠是在字符串参数中对第二个反斜杠进行转义,第二个反斜杠用于在property中进行转义)
var deepCss = { '.link': { '[target]': 42 } }expect(deepCss).to.have.deep.property('//.link.//[target//]', 42)
.any
在keys断言之前使用any标记(与all相反)
expect(foo).to.have.any.keys('bar', 'baz')
.all
在keys断言之前使用all标记(与any相反)
expect(foo).to.have.all.keys('bar', 'baz')
.a(type) / .an(type)
type:String,被测试的值的类型
a和an断言即可作为语言链又可作为断言使用
// 类型断言expect('test').to.be.a('string');expect({ foo: 'bar' }).to.be.an('object');expect(null).to.be.a('null');expect(undefined).to.be.an('undefined');expect(new Error).to.be.an('error');expect(new Promise).to.be.a('promise');expect(new Float32Array()).to.be.a('float32array');expect(Symbol()).to.be.a('symbol');// es6 overridesexpect({[Symbol.toStringTag]:()=>'foo'}).to.be.a('foo');// language chainexpect(foo).to.be.an.instanceof(Foo);
.include(value) / contains(value)
value:Object | String | Number
include()和contains()即可作为属性类断言前缀语言链又可作为作为判断数组、字符串是否包含某值的断言使用。当作为语言链使用时,常用于key()断言之前
新闻热点
疑难解答
图片精选