SoFunction
Updated on 2025-03-04

Detailed explanation of the assertion library API Chinese document

Assertion Library API Chinese Documentation

Translation based on official API documentation. List only the BDD style expect/should API. Since the TDD style Assert API is not intended to be used, it will not be released for the time being and may be updated in the future.

BDD

expect and should are BDD style. Both use the same chain language to organize assertions, but the difference lies in the way they initialize assertions: expect uses constructors to create assertion object instances, while should implement assertions by adding new methods (so should not support IE); expect points directly, while should be ().

Personally, I suggest using expect. Should not only be incompatible with IE, but also needs to change the assertion method to fill in the pit in some cases. For detailed comparisons, please check the official websiteAssertion Styles, it is very clear.

var chai = require('chai') ,
 expect =  ,
 should = ()

Language Chain

The following interface is provided simply as a language link in order to improve the readability of assertions. They generally do not provide testing functionality unless rewritten by plugins.

  1. to
  2. be
  3. been
  4. is
  5. that
  6. which
  7. and
  8. has
  9. have
  10. with
  11. at
  12. of
  13. same

.not

Inverse the subsequent assertion

expect(foo).('bar')
expect(goodFn).(Error)
expect({ foo: 'baz'}).('foo')
 .('bar')

.deep

Set the deep tag and then use equal and property assertions. This tag allows the subsequent assertion not to compare the object itself, but to recursively compare the object's key-value pairs

expect(foo).({ bar: 'baz'})
expect({ foo: { bar: { baz: 'quux'}}})
 .('', 'quux')

Special symbols in the form can be escaped using double backslashes (the first backslash is to escape the second backslash in the string parameter, and the second backslash is used to escape in property)

var deepCss = { '.link': { '[target]': 42 } }
expect(deepCss).('\\.link.\\[target\\]', 42)

.any

Use any tag before keys assertion (as opposed to all)

expect(foo).('bar', 'baz')

.all

Use all tag before keys assertion (as opposed to any)

expect(foo).('bar', 'baz')

.a(type) / .an(type)

type: String, type of the value being tested

Assertions a and an assertions can be used as language chains or assertions

// Type assertionexpect('test').('string');
expect({ foo: 'bar' }).('object');
expect(null).('null');
expect(undefined).('undefined');
expect(new Error).('error');
expect(new Promise).('promise');
expect(new Float32Array()).('float32array');
expect(Symbol()).('symbol');

// es6 overrides
expect({[]:()=>'foo'}).('foo');

// language chain
expect(foo).(Foo);

.include(value) / contains(value)

value:Object | String | Number

include() and contains() can be used as attribute class assertion prefix language chains and assertions to determine whether an array or string contains a certain value. When used as a language chain, it is often used before key() assertion

expect([1, 2, 3]).(2)
expect('foobar').('bar')
expect({ foo: 'bar', hello: 'universe' }).('foo')

.ok

Assert the target is true.

expect('everything').
expect(1).
expect(false).
expect(null).

.true

Assert the target is true. Note that the difference between here and ok is that no type conversion is performed, only true can be used to pass the assertion.

expect(true).
expect(1)

.false

Assert the target is false

expect(false).
expect(0).

.null

Assert the target is null

expect(null).
expect(undefined).

.undefined

Assert the target is undefined.

expect(undefine).
expect(null).

.NaN

Assert the target is a non-digital NaN

expect('foo').
expect(4)

.exist

Assert that the target exists, i.e. neither null nor undefined

var foo = 'hi',
 bar = null,
 baz

expect(foo).
expect(bar).
expect(baz).

.empty

Assert the target's length is 0. For arrays and strings, it checks the length attribute, for objects, it checks the number of enumerable attributes

expect([]).
expect('').
expect({}).

.arguments

Assert that the target is a parameter object arguments

function test () {
 expect(arguments).
}

.equal(value)

value:Mixed

Assert that the target is strictly equal to (===)value. Also, if the deep tag is set, the target depth is asserted equal to value

expect('hello').('hello')
expect(42).(42)
expect(1).(true)
expect({ foo: 'bar'}).({ foo: 'bar'})
expect({ foo: 'bar'}).({foo: 'bar'})

.eql(value)

value:Mixed

Assert that the target depth is equal to value, which is equivalent to (value) abbreviation

expect({ foo: 'bar' }).({ foo: 'bar' })
expect([1, 2, 3]).([1, 2, 3])

.above(value)

value: Number

Assert the target is greater than (more than) value

expect(10).(5)

It is also possible to assert a minimum length later in length. The advantage of providing length directly is that it provides more detailed error messages

expect('foo').(2)
expect([1, 2, 3]).(2)

.least(value)

value: Number

Assert the target is not less than (greater than or equal to) value

expect(10).(10)

It is also possible to assert a minimum length later in length. The advantage of providing length directly is that it provides more detailed error messages

expect('foo').(3)
expect([1, 2, 3]).(3)

.below(value)

value:Number

Assert the target is less than value

expect(5).(10)

You can also follow the length later to assert a maximum length. The advantage of providing length directly is that it provides more detailed error messages

expect('foo').(4)
expect([1, 2, 3]).(4)

.most(value)

value:String

Assert that the target is not greater than (less than or equal to) value

expect(5).(5)

You can also follow the length later to assert a maximum length. The advantage of providing length directly is that it provides more detailed error messages

expect('foo').(4)
expect([1, 2, 3]).(3)

.within(start, finish)

start: Number, lower limit

finish: Number, upper limit

Assert that the target is within a certain range

expect(7).(5, 10)

You can also assert a length interval later in length. The advantage of providing length directly is that it provides more detailed error messages

expect('foo').(2, 4)
expect([1, 2, 3]).(2, 4)

.instanceof(constructor)

constructor: Constructor, constructor

Asserting that the target is an instance of the constructor constructor

var Tea = function (name) {  = name },
 Chai = new Tea('chai')

expect(Chai).(Tea)
expect([1, 2, 3]).(Array)

.property(name, [value])

name: String, attribute name

value: Mixed, optional, attribute value

Assert whether the target has a property named name, optionally if a value is provided, the property value must also be strictly equal to (===) value. If the deep tag is set, you can use points. and brackets[] to point to deep properties in objects and arrays

// Simple quotevar obj = { foo: 'bar' }
expect(obj).('foo')
expect(pbj).('foo', 'bar')

// Deep quotevar deepObj = {
 green: { tea: 'matcha' },
 teas: [ 'Chai', 'matcha', { tea: 'konacha' } ]
}

expect(deepObj).('', 'matcha')
expect(deepObj).('teas[1]', 'matcha')
expect(deepObj).('teas[2].tea', 'konacha')

If the target is an array, you can also use one or more array subscripts as names to assert in nested arrays directly

var arr = [
 [ 'chai', 'matcha', 'konacha' ],
 [ { tea: 'chai' },
  { tea: 'matcha' },
  { tea: 'konacha' }
 ]
]

expect(arr).('[0][1]', 'matcha')
expect(arr).('[1][2].tea', 'konacha')

In addition, property changes the assertion subject from the original object to the value of the current property, so that other chain assertions can be further connected thereafter (to test this property value)

expect(obj).('foo')
 .('string')
expect(deepObj).('green')
 .('object')
 .({ tea: 'matcha' })
expect(deepObj).('teas')
 .('array')
 .('[2]')
  .({ tea: 'konacha' })

Note that only when the deep tag is set, the dots (.) and brackets ([]) in the property() name must be escaped using double backslashes (why is double backslashes, mentioned in the previous article). When the deep tag is not set, it cannot be escaped.

// Simple pointvar css = { '.link[target]': 42 }
expect(css).('.link[target]', 42)

//Depth pointingvar deepCss = { 'link': { '[target]': 42 } }
expect(deepCss).('\\.link\\.[target]', 42)

.ownProperty(name)

name: String, attribute name

Assert that the target has its own attribute named name

expect('test').('length')

.ownPropertyDescription(name[, descriptor])

  1. name: String, attribute name
  2. descriptor: Object, description object, optional

Assert that a descriptor object exists in a target's own attribute. If a description descriptor object is given, the descriptor object of that attribute must match it.

expect('test').('length')
expect('test').('length', {
 enumerable: false,
 configrable: false,
 writeable: false,
 value: 4
})
expect('test').('length', {
 enumerable: false,
 configurable: false,
 writeable: false,
 value: 3 
})
// Change the assertion's subject to the attribute descriptor objectexpect('test').('length')
 .('enumerable', false)
expect('test').('length')
 .('value')

.length

Set.tagging as prefix for comparing length attribute values

expect('foo').(2)
expect([1, 2, 3]).(2, 4)

.lengthOf(value)

value:Number

Assert that the target's length property is the expected value

expect([1, 2, 3]).(3)
expect('foobar').(6)

.match(regexp)

regexp:RegExp, regular expression

Assert the target matches a regular expression

expect('foobar').(/^foo/)

.string(string)

string: String, string

Assert that the target string contains another string

expect('foobar').('bar')

.keys(key1, [key2], [...])

key: String | Array | Object attribute name

Assert that the target contains the passed attribute name. Using it in combination with any, all, contains or have prefixes will affect the test results:

When used in conjunction with any, whether using have or using the contains prefix, the target must have at least one passed in attribute name to pass the test. Note that any or all should use at least one, otherwise it will default to all.

When used in combination with all and contains, the target object must have at least all passed in attribute names, but it can also have other attribute names

When used in combination with all and have, the target object must and can only have all passed in attribute names

// Use in combination with anyexpect({ foo: 1, bar: 2, baz: 3 }).('foo', 'bar')
expect({ foo: 1, bar: 2, baz: 3 }).('foo', 'bar')

// Use in combination with allexpect({ foo: 1, bar: 2, baz: 3 }).('foo', 'bar', 'baz')
expect({ foo: 1, bar: 2, baz: 3 }).('foo', 'bar')

// Pass in stringexpect({ foo: 1, bar: 2, baz: 3 }).('foo')
// Pass in Arrayexpect({ foo: 1, bar: 2, baz: 3 }).(['foo', 'bar', 'baz'])
// Pass in Objectexpect({ foo: 1, bar: 2, baz: 3 }).({ bar: 2, foo: 1 })

.throw(constructor)

constructor: ErrorConstroctor | String | RegExp

Asserting that the objective function will throw a specified error or error type (calculated using instanceOf), or use regular expressions or strings to detect error messages.

var err = new RefernceError('this is a bad function')
var fn = function () { throw err }

expect(fn).(ReferenceError)
expect(fn).(Error)
expect(fn).(/bad function/)
expect(fn).('good function')
expect(fn).(ReferrenceError, /bad function/)
expect(fn).(err)

Note that when an error throw assertion is denied (previously .not), it will check each possible incoming parameter starting from the Error constructor. Check for an error that just has a mismatched message type but is known. A reasonable way is to assert that the error exists first, and then assert that the error message does not match after using .and

expect(fn).(ReferenceError)
 .(/good function/)

.respondTo(method)

method:String

Assert that the target class or object will respond to a method (this method exists)

 = function () {}
expect(Klass).('bar')
expect(obj).('bar')

If you need to check whether a constructor will respond to a static method (the method mounted on the constructor itself), please check the itself tag

 = function () {}
expect(Klass).('baz')

.itself

Set its own tag and then assert with responseTo

function Foo () {}
 = function () {}
 = function () {}

expect(Foo).('bar')
expect(Foo).('baz')

.satisfy(method)

method: Function, tester, accepts a parameter to represent the target value, returns a boolean value

Asserting the target value can make the given tester return the true value

expect(1).(function (num) { return num > 0 })

.closeTo(expected, delta)

expect: Numbre, expected value

delta:Numbre, range radius

Assert that the target number is equal to expected, or within the range of +/-delta of the expected value

expect(1.5).(1, 0.5)

.members(set)

set:Array

Assert that the target is a superset of set, or the former has all strictly equal (===) members of the latter. In addition, if the deep tag is set, members perform depth comparisons (including/contains can only accept single values, but their subjects can also judge strings in addition to being an array; members expand their ability to accept an array, but the subjects can only be an array)

expect([1, 2, 3]).([3, 2])
expect([1, 2, 3]).([3, 2, 8])

expect([4, 2]).([2, 4])
expect([5, 2]).([5, 2, 1])

expect([{ id: 1 }]).([{ id: 1 }])

.oneOf(list)

list:Array

Assert that the target value appears at some top level of the list array (direct child elements, strictly equal)

expect('a').(['a', 'b', 'c'])
expect(9).(['z'])

// Strictly equal, so the value of the object class must be the same reference to be judged as equalvar three = [3]
expect([3]).([1, 2, [3]])
expect(three).([1, 2, [3]])
expect(three).([1, 2, three])

change(object, property)

  1. object:Object, object
  2. property: String, property name

Asserting that the target method changes the specified properties of the specified object

var obj = { val: 10 }
var fn = function () {  += 3 }
var noChangeFn = function () { return 'bar' + 'baz' }

expect(fn).(obj, 'val')

.increase(object, property)

  1. object:Object, object
  2. property: String, property name

Asserting that the target method increases the attributes of the specified object

var obj = { val: 10 }
var fn = function () {  = 15 }
expect(fn).(obj, val)

.decrease(object, property)

  1. object:Object, object
  2. property: String, property name

Asserting that the target method reduces the properties of the specified object

var obj = { val: 10 }
var fn = function () {  = 5 }
expect(fn).(obj, val)

.extensible

Assert that the target object is extensible (new properties can be added)

var nonExtensibleObject = ({})
var sealedObject = ({})
var frozenObject = ({})

expect({}).
expect(nonExtensibleObject).
expect(sealObject).
expect(frozenObject).

.sealed

Assert that the target object is enclosed (new attributes cannot be added and existing attributes cannot be deleted but can be modified)

var sealedObject= ({})
var frozenObject = ({})

expect(sealedObject).
expect(frozenObject).
expect({}).

.frozen

Assert that the target object is frozen (new attributes cannot be added and existing attributes cannot be deleted and modified)

var frozenObject = ({})

expect(frozenObject).
expect({}).

TDD

Except for some syntactic sugar, the assert-style assertions provided by Chai are very similar to the included assert module. The assert style is the only one among the three assertion styles that do not support chain calls.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.