Detailed explanation of the Chinese documentation of the Chai. js assertion library API, detailed explanation of the chai. js assertion api

Source: Internet
Author: User

Detailed explanation of the Chinese documentation of the Chai. js assertion library API, detailed explanation of the chai. js assertion api

Chai. js assertion library API Chinese Document

Based on chai. js official API documentation translation. Only list the APIs in the BDD style. The TDD-style Assert API is not intended for use and is not available for the time being. It may be updated later.

BDD

Except CT and shoshould are in the BDD style. They use the same chained language to organize assertions, but they differ in the way they initialize assertions: Except CT uses constructors to create asserted object instances, however, the value of shocould is Object. the new prototype method is used to implement assertion (therefore, shocould does not support IE); reverse CT directly points to chai. rollback CT, while shocould is chai. shocould ().

In my personal opinion, we recommend using reverse CT. shocould is not only incompatible with IE, but also needs to change the assertion method in some cases to fill in. For more information, see Assertion Styles on the official website.

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

Language chain

The following interface is provided as a language chain to improve the readability of assertions. Unless modified by the plug-in, they generally do not provide test functions.

  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

Backend the assertion

expect(foo).to.not.equal('bar')expect(goodFn).to.not.throw(Error)expect({ foo: 'baz'}).to.have.property('foo') .and.not.equal('bar')

. Deep

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

expect(foo).to.deep.equal({ bar: 'baz'})expect({ foo: { bar: { baz: 'quux'}}}) .to.have.deep.property('foo.bar.baz', 'quux')

Special characters in deep. property can be escaped using double backslash (the first backslash is used to escape the second backslash in the string parameter, and the second backslash is used to escape in the property)

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

. Any

Use the any mark (opposite to all) before the keys assertion)

expect(foo).to.have.any.keys('bar', 'baz')

. All

Use the all mark (opposite to any) before the keys asserted)

expect(foo).to.have.all.keys('bar', 'baz')

. A (type)/. an (type)

Type: String, type of the tested value

A and an assertions can be used as language chains and can be used as assertions.

// Type assertion CT ('test '). to. be. a ('string'); CT ({foo: 'bar '}). to. be. an ('object'); expect CT (null ). to. be. a ('null'); Country CT (undefined ). to. be. an ('undefined'); wrong CT (new Error ). to. be. an ('error'); wrong CT (new Promise ). to. be. a ('Promise '); reverse CT (new Float32Array ()). to. be. a ('float32array'); Symbol CT (Symbol ()). to. be. a ('symbol'); // es6 overridesexpect ({[symbol. toStringTag] :() => 'foo '}). to. be. a ('foo'); // language chainduplicate CT (foo ). to. be. an. instanceof (Foo );

. Include (value)/contains (value)

Value: Object | String | Number

Include () and contains () can be used as attribute class assertions prefix language chains and can be used as assertions to determine whether an array or string contains a certain 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')

. OK

The asserted target is the true value.

expect('everything').to.be.okexpect(1).to.be.okexpect(false).to.not.be.okexpect(null).to.not.be.ok

. True

The asserted object is true. Note that the difference between this parameter and OK is that no type conversion is performed. Only true can be used through assertions.

expect(true).to.be.trueexpect(1)to.not.be.true

. False

Assertion target is false

expect(false).to.be.falseexpect(0).to.not.be.false

. Null

Assertion target is null

expect(null).to.be.nullexpect(undefined).to.not.be.null

. Undefined

The assertion target is undefined.

expect(undefine).to.be.undefinedexpect(null).to.not.be.undefined

. NaN

The assertion target is a non-digital NaN.

expect('foo').to.be.nullexpect(4)to.not.be.null

. Exist

Assertion target exists, that is, non-null or non-undefined

var foo = 'hi', bar = null, bazexpect(foo).to.existexpect(bar).to.not.existexpect(baz).to.not.exist

. Empty

The length of the assertion target is 0. For arrays and strings, it checks the length attribute. For objects, it checks the number of enumerated attributes.

expect([]).to.be.emptyexpect('').to.be.emptyexpect({}).to.be.empty

. Arguments

The assertion target is a parameter object arguments

function test () { expect(arguments).to.be.arguments}

. Equal (value)

Value: Mixed

The assertion target is strictly equal to (=) value. In addition, if the deep mark is set, the asserted target depth is equal to the 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'})

. Eql (value)

Value: Mixed

Assertion Target Depth equals to value, equivalent to the abbreviation of deep. equal (value)

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

. Above (value)

Value: Number

The asserted target is greater than (more than) value.

expect(10).to.be.above(5)

You can also assert a minimum length after the length. The advantage of providing length is that more detailed error messages are provided.

expect('foo').to.have.length.above(2)expect([1, 2, 3]).to.have.length.above(2)

. Least (value)

Value: Number

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

expect(10).to.be.at.least(10)

You can also assert a minimum length after the length. The advantage of providing length is that more detailed error messages are provided.

expect('foo').to.have.length.of.at.least(3)expect([1, 2, 3]).to.have.length.of.at.least(3)

. Below (value)

Value: Number

Assertion target is smaller than value

expect(5).to.be.below(10)

You can also assert the maximum length after the length. The advantage of providing length is that more detailed error messages are provided.

expect('foo').to.have.length.below(4)expect([1, 2, 3]).to.have.length.below(4)

. Most (value)

Value: String

The asserted target is not greater than (less than or equal to) value.

expect(5).to.be.at.most(5)

You can also assert the maximum length after the length. The advantage of providing length is that more detailed error messages are provided.

expect('foo').to.have.length.of.at.most(4)expect([1, 2, 3]).to.have.length.of.at.most(3)

. Within (start, finish)

Start: Number, lower limit

Finish: Number, Upper Limit

Asserted target within a certain range

expect(7).to.be.within(5, 10)

You can also assert a length range after the length. The advantage of providing length is that more detailed error messages are provided.

expect('foo').to.have.length.within(2, 4)expect([1, 2, 3]).to.have.length.within(2, 4)

. Instanceof (constructor)

Constructor: Constructor, constructor

The assertion target is an instance of 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)

. Property (name, [value])

Name: String, attribute name

Value: Mixed, optional, attribute value

Whether the asserted target has an attribute named name. (optional) If value is provided, the attribute value must be strictly equal to (=) value. If the deep tag is set, you can use dot. and brackets [] to point to the deep attributes in the object and array.

// Simple reference var obj = {foo: 'bar'} expect CT (obj ). to. have. property ('foo') CT (pbj ). to. have. property ('foo', 'bar') // deep reference var deepObj = {green: {tea: 'matcha '}, teas: ['chai', 'matcha ', {tea: 'konacha'}]} Your CT (deepObj ). to. have. deep. property ('green. tea ', 'matcha') CT (deepObj ). to. have. deep. property ('teas [1] ', 'matcha') CT (deepObj ). to. have. deep. property ('teas [2]. tea ', 'konacha ')

If the target is an array, you can use one or more array subscript as name to assert deep. property in the nested array.

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')

In addition, property changes the assertion subject (subject) from the original object to the current attribute value, so that other chained assertions can be further connected later (to test the attribute 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' })

Note that only when deep flag is set, the vertex (.) in property () name (.) and brackets ([]) must be escaped using the double backslash \ (why is it a double backslash, as mentioned above). When the deep mark is not set, it cannot be escaped.

// Point to var css = {'. link [target] ': 42} Keep CT (css ). to. have. property ('. link [target] ', 42) // point to var deepCss in depth = {'link': {' [target] ': 42} reverse CT (deepCss ). to. have. deep. property ('\\. link \\. [target] ', 42)

. OwnProperty (name)

Name: String, attribute name

The asserted target has its own property named name.

expect('test').to.have.ownProperty('length')

. OwnPropertyDescription (name [, descriptor])

  1. Name: String, attribute name
  2. Descriptor: Object, description Object, optional

An existing attribute of the assertion target has a descriptor object. If a descroptor descriptor object is specified, the descriptor object of this attribute must match it.

CT ('test '). to. have. ownPropertyDescriptor ('length') CT ('test '). to. have. ownPropertyDescriptor ('length', {enumerable: false, configrable: false, writeable: false, value: 4}) CT ('test '). not. to. have. ownPropertyDescriptor ('length', {enumerable: false, retriable: false, writeable: false, value: 3 }) // change the assertion subject to the property descriptor object benchmark CT ('test '). to. have. ownPropertyDescriptor ('length '). to. have. property ('enumerable', false) CT ('test '). to. have. ownPropertyDescriptor ('length '). to. have. keys ('value ')

. Length

Set the. have. length tag as the prefix for comparing the length attribute values

expect('foo').to.have.length.above(2)expect([1, 2, 3]).to.have.length.within(2, 4)

. LengthOf (value)

Value: Number

The length attribute of the asserted target is the expected value.

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

. Match (regexp)

Regexp: RegExp, Regular Expression

The assertion Target matches a regular expression.

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

. String (string)

String: String, string

Assertion target string contains another string

expect('foobar').to.have.string('bar')

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

Key: String | Array | Object attribute name

The assertion target contains the passed attribute name. Combined with any, all, contains or have prefixes will affect the test results:

When used with any, whether have or contains prefix is used, the target must have at least one passed attribute name to pass the test. Note that either any or all should use at least one. Otherwise, the default value is all.

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

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

// Use reverse CT ({foo: 1, bar: 2, baz: 3}) in combination with any }). to. have. any. keys ('foo', 'bar') CT ({foo: 1, bar: 2, baz: 3 }). to. contains. any. keys ('foo', 'bar') // use keep CT ({foo: 1, bar: 2, baz: 3}) in combination with all }). to. have. all. keys ('foo', 'bar', 'baz') CT ({foo: 1, bar: 2, baz: 3 }). to. contains. all. keys ('foo', 'bar') // input stringexpect ({foo: 1, bar: 2, baz: 3 }). to. have. any. keys ('foo') // input Arrayexpect ({foo: 1, bar: 2, baz: 3 }). to. have. all. keys (['foo', 'bar', 'baz']) // input Objectexpect ({foo: 1, bar: 2, baz: 3 }). to. have. any. keys ({bar: 2, foo: 1 })

. Throw (constructor)

Constructor: ErrorConstroctor | String | RegExp

The asserted target function throws a specified error or error type (Calculated using instanceOf). You can also 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).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)

Note: When an Error throwing asserted is denied (there is a. not), it checks the possible input parameters from the Error constructor in sequence. Check for an error that only indicates that the message type does not match but is known. A reasonable method is to assert that the error exists first, and then use. and to assert that the error message does not match.

expect(fn).to.throw(ReferenceError) .and.not.throw(/good function/)

. RespondTo (method)

Method: String

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

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

If you need to check whether a constructor responds to a static method (the method attached to the constructor itself), check the itself flag.

Klass.baz = function () {}expect(Klass).itself.to.respondTo('baz')

. Itself

Set the itself flag and then use respondTo to assert

function Foo () {}Foo.bar = function () {}Foo.prototype.baz = function () {}expect(Foo).itself.to.respondTo('bar')expect(Foo).itself.not.to.respond('baz')

. Satisfy (method)

Method: Function, tester. If one parameter is accepted to indicate the target value, a Boolean value is returned.

Assertion target value allows the given tester to return the true value

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

. CloseTo (expected, delta)

Wrong CT: Numbre, Expected Value

Delta: Numbre, range radius

Assertion target number is equal to expected, or within the range of +/-delta expected Value

expect(1.5).to.be.closeTo(1, 0.5)

. Members (set)

Set: Array

The assertion target is the superset of the set, or the former has all strictly equal (=) members of the latter. In addition, if deep tag is set, deep comparison is performed for members (include/contains can only accept a single value, but their subject can be an array or a string; members expands their capabilities to accept an array, but the subject can only be an array)

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 }])

. OneOf (list)

List: Array

Assertion target values appear at a top-level position of the list array (directly sub-elements, strictly equal)

CT ('A '). to. be. oneOf (['A', 'B', 'C']) CT (9 ). to. not. be. oneOf (['Z']) // strictly equal, therefore, the object class value must be the same reference before it can be considered as equal var three = [3] CT ([3]). to. not. be. oneOf ([1, 2, [3]) CT (three ). to. not. be. oneOf ([1, 2, [3]) CT (three ). to. be. oneOf ([1, 2, three])

Change (object, property)

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

The assertion target method changes the specified attribute 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')

. Increase (object, property)

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

The assertion target method adds the attribute of the specified object.

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

. Decrease (object, property)

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

The assertion target method reduces the attribute of the specified object.

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

. Extensible

Assertion target object is extensible (new attributes can be added)

var nonExtensibleObject = Object.preventExtensions({})var sealedObject = Object.seal({})var frozenObject = Object.freeze({})expect({}).to.be.extensibleexpect(nonExtensibleObject).to.not.be.extensibleexpect(sealObject).to.not.be.extensibleexpect(frozenObject).to.not.be.extensible

. Sealed

Assertion target object is closed (new attributes cannot be added and existing attributes cannot be deleted but can be modified)

var sealedObject= Object.seal({})var frozenObject = Object.freeze({})expect(sealedObject).to.be.sealedexpect(frozenObject).to.be.sealedexpect({}).to.not.be.sealed

. Frozen

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

var frozenObject = Object.freeze({})expect(frozenObject).to.be.frozenexpect({}).to.not.be.frozen

TDD

In addition to some syntactic sugar, the assert-style assertions provided by Chai are very similar to those contained in node. js. The assert style is the only one of the three asserted styles that does not support chained calling.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.