How does the chai expect function work?

后端 未结 2 1063
别跟我提以往
别跟我提以往 2020-12-17 16:35

From chai\'s api you\'ve got code like this:

.exist

Asserts that the target is neither null nor undefined.

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

expect         


        
2条回答
  •  暖寄归人
    2020-12-17 17:21

    When you call expect(foo), a new Assertion object is instantiated.

    to, have, with, and similar properties do nothing but to return that Assertion instance. They are only for readability.

    However, in your example, exists, is actually something that runs an assertion.

    Its a property. They way properties are added to Assertion is that they are defined as getter functions as you can see here.

    expect(foo).to.exist could be broken down to this:

    const assertion = new Assertion;
    assertion.exists;
    

    assertion.exists is added to the assertion object with a getter. That means when you execute assertion.exists, to evaluate the value of assertion.exists, a function that was earlier provided to addProperty is executed.

    You can read more about getter functions.

提交回复
热议问题