Official API document translation based on chai. Js. Only BDD style Expect /should apis are listed. The TDD style Assert API is not intended to be used, so it may be updated later.
BDD
Expect and should are BDD style, and they use the same chained language to organize assertions, but differ in how they initialize assertions: Expect uses constructors to create predicate Object instances, while should implements assertions by adding new methods to Object.prototype (so should doesn’t support IE); Expect points directly to chai. Expect, and should to chai. Should ().
I personally recommend using Expect. Should is not only incompatible with IE, but in some cases requires a change of assertion to fill in the holes. Assertion Styles can be found here.
var chai = require('chai') ,
expect = chai.expect ,
should = chai.should()
Copy the code
The chain of language
The following interface is provided purely as a language chain to improve the readability of assertions. They generally do not provide testing functionality unless overwritten by plug-ins.
- to
- be
- been
- is
- that
- which
- and
- has
- have
- with
- at
- of
- same
.not
The following assertion is reversed
expect(foo).to.not.equal('bar')
expect(goodFn).to.not.throw(Error)
expect({ foo: 'baz'}).to.have.property('foo')
.and.not.equal('bar')
Copy the code
.deep
Set the deep flag, then use equal and property assertions. This tag allows subsequent assertions not to compare the object itself, but to recursively compare the object’s key-value pairs
expect(foo).to.deep.equal({ bar: 'baz'})
expect({ foo: { bar: { baz: 'quux'}}})
.to.have.deep.property('foo.bar.baz'.'quux')
Copy the code
Special symbols in deep.property can be escaped using double backslashes (the first backslash is used to escape the second backslash in string arguments, and the second backslash is used to escape in property)
var deepCss = { '.link': { '[target]': 42 } }
expect(deepCss).to.have.deep.property('\\.link.\\[target\\]'.42)
Copy the code
.any
Use any before keys assertion (as opposed to all)
expect(foo).to.have.any.keys('bar'.'baz')
Copy the code
.all
Use all before keys assertion (as opposed to any)
expect(foo).to.have.all.keys('bar'.'baz')
Copy the code
.a(type) / .an(type)
- Type: String, the type of the value being tested
A and AN assertions can be used as both language chains and assertions
// Type assertion
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 overrides
expect({[Symbol.toStringTag]:(a)= >'foo'}).to.be.a('foo');
// language chain
expect(foo).to.be.an.instanceof(Foo);
Copy the code
.include(value) / contains(value)
- Value: the Object | String | Number
Include () and contains() can be used as attribute class assertions to prefix language chains and as assertions to determine whether an array or string contains a value. When used as a language chain, it is often used before key() assertions
expect([1.2.3]).to.include(2)
expect('foobar').to.include('bar')
expect({ foo: 'bar'.hello: 'universe' }).to.include.keys('foo')
Copy the code
.ok
Asserts that the target is true.
expect('everything').to.be.ok
expect(1).to.be.ok
expect(false).to.not.be.ok
expect(null).to.not.be.ok
Copy the code
.true
The assertion target is true. Note that the difference with OK is that there is no type conversion and only true can pass the assertion
expect(true).to.be.true
expect(1)to.not.be.true
Copy the code
.false
Assert that the target is false
expect(false).to.be.false
expect(0).to.not.be.false
Copy the code
.null
Asserts that the target is NULL
expect(null).to.be.null
expect(undefined).to.not.be.null
Copy the code
.undefined
Assert that the target is undefined.
expect(undefine).to.be.undefined
expect(null).to.not.be.undefined
Copy the code
.NaN
Assert that the target is a non-numeric NaN
expect('foo').to.be.null
expect(4)to.not.be.null
Copy the code
.exist
Asserts that the target exists, neither null nor undefined
var foo = 'hi',
bar = null,
baz
expect(foo).to.exist
expect(bar).to.not.exist
expect(baz).to.not.exist
Copy the code
.empty
Asserts that the length of the target is 0. It checks the length attribute for arrays and strings, and the number of enumerable attributes for objects
expect([]).to.be.empty
expect(' ').to.be.empty
expect({}).to.be.empty
Copy the code
.arguments
The assertion target is a parameter object arguments
function test () {
expect(arguments).to.be.arguments
}
Copy the code
.equal(value)
- Value: Mixed
Assert that the target is strictly equal to (===)value. Also, if the deep flag is set, the target depth is asserted to be equal to value
expect('hello').to.equal('hello')
expect(42).to.equal(42)
expect(1).to.not.equal(true)
expect({ foo: 'bar'}).to.not.equal({ foo: 'bar'})
expect({ foo: 'bar'}).to.deep.equal({foo: 'bar'})
Copy the code
.eql(value)
- Value: Mixed
Asserts that the target depth is equal to value, which is a shorthand for deep.equal(value)
expect({ foo: 'bar' }).to.eql({ foo: 'bar' })
expect([1.2.3]).to.eql([1.2.3])
Copy the code
.above(value)
- Value: Number
Assert that the target is greater than (or greater than) value
expect(10).to.be.above(5)
Copy the code
It can also be followed by length to assert a minimum length. The benefit of providing a more detailed error message than providing the length directly
expect('foo').to.have.length.above(2)
expect([1.2.3]).to.have.length.above(2)
Copy the code
.least(value)
- Value: Number
Assert that the target is not less than (greater than or equal to) value
expect(10).to.be.at.least(10)
Copy the code
It can also be followed by length to assert a minimum length. The benefit of providing a more detailed error message than providing the length directly
expect('foo').to.have.length.of.at.least(3)
expect([1.2.3]).to.have.length.of.at.least(3)
Copy the code
.below(value)
- Value: Number
Assert that the target is less than value
expect(5).to.be.below(10)
Copy the code
It can also be followed by length to later assert a maximum length. The benefit of providing a more detailed error message than providing the length directly
expect('foo').to.have.length.below(4)
expect([1.2.3]).to.have.length.below(4)
Copy the code
.most(value)
- Value: a String
Assert that the target is not greater than (less than or equal to) value
expect(5).to.be.at.most(5)
Copy the code
It can also be followed by length to later assert a maximum length. The benefit of providing a more detailed error message than providing the length directly
expect('foo').to.have.length.of.at.most(4)
expect([1.2.3]).to.have.length.of.at.most(3)
Copy the code
.within(start, finish)
- Start: Number, lower limit
- Finish: Number, upper limit
Asserts that the target is within an interval
expect(7).to.be.within(5.10)
Copy the code
Length can also be followed by length to assert a length range. The benefit of providing a more detailed error message than providing the length directly
expect('foo').to.have.length.within(2.4)
expect([1.2.3]).to.have.length.within(2.4)
Copy the code
.instanceof(constructor)
- Constructor: constructor
The assertion target is an instance of the constructor
var Tea = function (name) { this.name = name },
Chai = new Tea('chai')
expect(Chai).to.be.an.instanceof(Tea)
expect([1.2.3]).to.be.an.instanceof(Array)
Copy the code
.property(name, [value])
- Name: String, attribute name
- Value: Mixed, optional, attribute value
Asserts whether the target has an attribute named name, optionally equal to (===) value if value is provided. If the deep flag is set, points can be used. And brackets [] to point to deep properties in objects and arrays
// Simple reference
var obj = { foo: 'bar' }
expect(obj).to.have.property('foo')
expect(pbj).to.have.property('foo'.'bar')
// Deep references
var deepObj = {
green: { tea: 'matcha' },
teas: [ 'Chai'.'matcha', { tea: 'konacha' } ]
}
expect(deepObj).to.have.deep.property('green.tea'.'matcha')
expect(deepObj).to.have.deep.property('teas[1]'.'matcha')
expect(deepObj).to.have.deep.property('teas[2].tea'.'konacha')
Copy the code
If the target is an array, you can also assert deep.property in a nested array directly using one or more array subscripts as names
var arr = [
[ 'chai'.'matcha'.'konacha'], [{tea: 'chai' },
{ tea: 'matcha' },
{ tea: 'konacha' }
]
]
expect(arr).to.have.deep.property('[0] [1]'.'matcha')
expect(arr).to.have.deep.property('[1][2].tea'.'konacha')
Copy the code
In addition, property changes the subject of the assertion from the original object to the value of the current property, allowing other chained assertions to be followed (to test against the property value)
expect(obj).to.have.property('foo')
.that.is.a('string')
expect(deepObj).to.have.property('green')
.that.is.an('object')
.that.deep.equals({ tea: 'matcha' })
expect(deepObj).to.have.property('teas')
.that.is.an('array')
.with.deep.property('[2]')
.that.deep.equals({ tea: 'konacha' })
Copy the code
Note that the dot (.) in the property() name is only set when the deep flag is set. And parentheses ([]) must be escaped with a double backslash \. When the deep flag is not set, it cannot be escaped
// Simple pointing
var css = { '.link[target]': 42 }
expect(css).to.have.property('.link[target]'.42)
// Depth pointing
var deepCss = { 'link': { '[target]': 42 } }
expect(deepCss).to.have.deep.property('\\.link\\.[target]'.42)
Copy the code
.ownProperty(name)
- Name: String, the attribute name asserts that the target has a name
name
Property of
expect('test').to.have.ownProperty('length')
Copy the code
.ownPropertyDescription(name[, descriptor])
- Name: String, attribute name
- Descriptor: Object, description Object, optional
A descriptor object exists for one of the assertion target’s own properties, and if a Descroptor descriptor object is given, the descriptor object for that property must match it
expect('test').to.have.ownPropertyDescriptor('length')
expect('test').to.have.ownPropertyDescriptor('length', {
enumerable: false.configrable: false.writeable: false.value: 4
})
expect('test').not.to.have.ownPropertyDescriptor('length', {
enumerable: false.configurable: false.writeable: false.value: 3
})
// Change the subject of the assertion to an attribute descriptor object
expect('test').to.have.ownPropertyDescriptor('length')
.to.have.property('enumerable'.false)
expect('test').to.have.ownPropertyDescriptor('length')
.to.have.keys('value')
Copy the code
.length
Sets the.have. Length flag as a prefix to compare the value of the length attribute
expect('foo').to.have.length.above(2)
expect([1.2.3]).to.have.length.within(2.4)
Copy the code
.lengthOf(value)
- Value: Number
Asserts that the length attribute of the target is the desired value
expect([1.2.3]).to.have.lengthOf(3)
expect('foobar').to.have.lengthOf(6)
Copy the code
.match(regexp)
- Regexp: regexp, regular expression
Assert that the target matches a regular expression
expect('foobar').to.match(/^foo/)
Copy the code
.string(string)
- String: string
Assert that the target string contains another string
expect('foobar').to.have.string('bar')
Copy the code
.keys(key1, [key2], […] )
- Key: String | Array | Object attribute names
The assertion target contains the name of the attribute passed in. Using the prefix any, all, contains, or have can affect the test results:
When used with any, the target must have at least one passed property name to pass the test, either with the have or contains prefix. Note that at least one of any or all should be used, otherwise the default is all
When used in combination with ALL and CONTAINS, the target object must have at least all of the attribute names passed in, but it can have other attribute names as well
When used in combination with all and have, the target object must and can only have all of the attribute names passed in
// Use with any
expect({ foo: 1.bar: 2.baz: 3 }).to.have.any.keys('foo'.'bar')
expect({ foo: 1.bar: 2.baz: 3 }).to.contains.any.keys('foo'.'bar')
// Use with all
expect({ foo: 1.bar: 2.baz: 3 }).to.have.all.keys('foo'.'bar'.'baz')
expect({ foo: 1.bar: 2.baz: 3 }).to.contains.all.keys('foo'.'bar')
/ / the incoming string
expect({ foo: 1.bar: 2.baz: 3 }).to.have.any.keys('foo')
/ / incoming Array
expect({ foo: 1.bar: 2.baz: 3 }).to.have.all.keys(['foo'.'bar'.'baz'])
/ / the incoming Object
expect({ foo: 1.bar: 2.baz: 3 }).to.have.any.keys({ bar: 2.foo: 1 })
Copy the code
.throw(constructor)
- Constructor: ErrorConstroctor | String | RegExp
The assertion target function throws a specified error or error type (evaluated using instanceOf), or can use a regular expression or string to detect the error message
var err = new RefernceError('this is a bad function')
var fn = function () { throw err }
expect(fn).to.throw(ReferenceError)
expect(fn).to.throw(Error)
expect(fn).to.throw(/bad function/)
expect(fn).to.not.throw('good function')
expect(fn).to.throw(ReferrenceError, /bad function/)
expect(fn).to.throw(err)
Copy the code
Note that when a throw assertion is negated (preceded by.not), it checks each possible argument in turn, starting with the Error constructor. A reasonable way to check for a known error with only a message type mismatch is to assert that the error exists, then use.and to assert that the error message does not match
expect(fn).to.throw(ReferenceError)
.and.not.throw(/good function/)
Copy the code
####.respondTo(method)
- Method: the String
Asserts that the target class or object responds to a method that exists
Klass.prototype.bar = function () {}
expect(Klass).to.respondTo('bar')
expect(obj).to.respondTo('bar')
Copy the code
If you need to check whether a constructor responds to a static method (a method mounted on the constructor itself), look at the Itself flag
Klass.baz = function () {}
expect(Klass).itself.to.respondTo('baz')
Copy the code
.itself
Set the Itself flag and then use the respondTo assertion
function Foo () {}
Foo.bar = function () {}
Foo.prototype.baz = function () {}
expect(Foo).itself.to.respondTo('bar')
expect(Foo).itself.not.to.respond('baz')
Copy the code
.satisfy(method)
- Method: Function, a tester that takes a parameter representing the target value and returns a Boolean value
Assert that the target value can return true for a given tester
expect(1).to.satisfy(function (num) { return num > 0 })
Copy the code
.closeTo(expected, delta)
- Expect: Numbre, expected value
- Delta: Numbre, range radius
Assert that the target number is expected, or within the expected +/-delta range
expect(1.5).to.be.closeTo(1.0.5)
Copy the code
.members(set)
- Set: Array
Asserts that the target is a superset of set, or that the former has all strictly equal (===) members of the latter. In addition, if the deep flag is set, the members can be compared in depth (include/ Contains can only accept a single value, but their subjects can be strings as well as arrays; Members extend their ability to accept an array, but only as a subject.)
expect([1.2.3]).to.include.members([3.2])
expect([1.2.3]).to.not.include.members([3.2.8])
expect([4.2]).to.have.members([2.4])
expect([5.2]).to.not.have.members([5.2.1])
expect([{ id: 1 }]).to.deep.include.members([{ id: 1 }])
Copy the code
.oneOf(list)
- List: Array
Asserts that the target value appears at some top level of the list array (direct children, strictly equal)
expect('a').to.be.oneOf(['a'.'b'.'c'])
expect(9).to.not.be.oneOf(['z'])
// Strict equality, so the values of the object class must be the same reference to be considered equal
var three = [3]
expect([3]).to.not.be.oneOf([1.2[3]])
expect(three).to.not.be.oneOf([1.2[3]])
expect(three).to.be.oneOf([1.2, three])
Copy the code
change(object, property)
- Object: object
- Property: String, the name of the property
The assertion target method changes the specified property of the specified object
var obj = { val: 10 }
var fn = function () { obj.val += 3 }
var noChangeFn = function () { return 'bar' + 'baz' }
expect(fn).to.change(obj, 'val')
Copy the code
.increase(object, property)
- Object: object
- Property: String, the name of the property
The assert target method increments the properties of the specified object
var obj = { val: 10 }
var fn = function () { obj.val = 15 }
expect(fn).to.increase(obj, val)
Copy the code
.decrease(object, property)
- Object: object
- Property: String, the name of the property
Asserting the target method reduces the attributes of the specified object
var obj = { val: 10 }
var fn = function () { obj.val = 5 }
expect(fn).to.decrease(obj, val)
Copy the code
.extensible
Assert that the target object is extensible (new attributes can be added)
var nonExtensibleObject = Object.preventExtensions({})
var sealedObject = Object.seal({})
var frozenObject = Object.freeze({})
expect({}).to.be.extensible
expect(nonExtensibleObject).to.not.be.extensible
expect(sealObject).to.not.be.extensible
expect(frozenObject).to.not.be.extensible
Copy the code
.sealed
Assert that the target object is closed (new attributes cannot be added and existing attributes cannot be removed but can be modified)
var sealedObject= Object.seal({})
var frozenObject = Object.freeze({})
expect(sealedObject).to.be.sealed
expect(frozenObject).to.be.sealed
expect({}).to.not.be.sealed
Copy the code
.frozen
Assert that the target object is frozen (no new attributes can be added and existing attributes cannot be deleted or modified)
var frozenObject = Object.freeze({})
expect(frozenObject).to.be.frozen
expect({}).to.not.be.frozen
Copy the code
TDD
Aside from some syntax sugar, the Assert style assertions provided by Chai are very similar to the Assert module included with Node.js. The Assert style is the only one of the three assertion styles that does not support chained calls. // TODO API reference