The plugin utilities are for those who want to extend Chai with their own set ofassertions. TheCore Plugin Concepts andBuilding a Helper guide tutorials are a great reference onhow to get started with your own assertions.
Adds a method to an object, such that the method can also be chained.
utils.addChainableMethod(chai.Assertion.prototype,'foo',function(str){varobj=utils.flag(this,'object');newchai.Assertion(obj).to.be.equal(str);});
Can also be accessed directly fromchai.Assertion
.
chai.Assertion.addChainableMethod('foo',fn,chainingBehavior);
The result can then be used as both a method assertion, executing bothmethod
andchainingBehavior
, or as a language chain, which only executeschainingBehavior
.
expect(fooStr).to.be.foo('bar');expect(fooStr).to.be.foo.equal('foo');
Definelength
as a getter on the given uninvoked method assertion. Thegetter acts as a guard against chaininglength
directly off of an uninvokedmethod assertion, which is a problem because it referencesfunction
’sbuilt-inlength
property instead of Chai’slength
assertion. When thegetter catches the user making this mistake, it throws an error with ahelpful message.
There are two ways in which this mistake can be made. The first way is bychaining thelength
assertion directly off of an uninvoked chainablemethod. In this case, Chai suggests that the user uselengthOf
instead. Thesecond way is by chaining thelength
assertion directly off of an uninvokednon-chainable method. Non-chainable methods must be invoked prior tochaining. In this case, Chai suggests that the user consult the docs for thegiven assertion.
If thelength
property of functions is unconfigurable, then returnfn
without modification.
Note that in ES6, the function’slength
property is configurable, so oncesupport for legacy environments is dropped, Chai’slength
property canreplace the built-in function’slength
property, and this length guard willno longer be necessary. In the mean time, maintaining consistency across allenvironments is the priority.
Adds a method to the prototype of an object.
utils.addMethod(chai.Assertion.prototype,'foo',function(str){varobj=utils.flag(this,'object');newchai.Assertion(obj).to.be.equal(str);});
Can also be accessed directly fromchai.Assertion
.
chai.Assertion.addMethod('foo',fn);
Then can be used as any other assertion.
expect(fooStr).to.be.foo('bar');
Adds a property to the prototype of an object.
utils.addProperty(chai.Assertion.prototype,'foo',function(){varobj=utils.flag(this,'object');newchai.Assertion(obj).to.be.instanceof(Foo);});
Can also be accessed directly fromchai.Assertion
.
chai.Assertion.addProperty('foo',fn);
Then can be used as any other assertion.
expect(myFoo).to.be.foo;
To be used as a compareFunction with Array.prototype.sort. Compares elementsusing inspect instead of default behavior of using toString so that Symbolsand objects with irregular/missing toString can still be sorted without aTypeError.
Ensures that the object being tested against is of a valid type.
utils.expectTypes(this,['array','object','string']);
Get or set a flag value on an object. If avalue is provided it will be set, else it willreturn the currently set value orundefined
ifthe value is not set.
utils.flag(this,'foo','bar');// setterutils.flag(this,'foo');// getter, returns `bar`
Returns theactual
value for an Assertion.
Construct the error message based on flagsand template tags. Template tags will returna stringified inspection of the object referenced.
Message template tags:
#{this}
current asserted object#{act}
actual value#{exp}
expected valueExtract the operator from error message.Operator defined is based on below linkhttps://nodejs.org/api/assert.html#assert_assert.
Returns theoperator
orundefined
value for an Assertion.
This allows the retrieval of directly-owned enumerable property names andsymbols of an object. This function is necessary because Object.keys onlyreturns enumerable property names, not enumerable property symbols.
This allows the retrieval of directly-owned enumerable property symbols of anobject. This function is necessary because Object.getOwnPropertySymbolsreturns both enumerable and non-enumerable property symbols.
This allows the retrieval of property names of an object, enumerable or not,inherited or not.
Echoes the value of a value. Tries to print the value outin the best way possible given the different types.
Helper function to check if Chai’s proxy protection feature is enabled. Ifproxies are unsupported or disabled via the user’s Chai config, then returnfalse. Otherwise, return true.
Determines if an object or an array matchescriteria to be inspected in-line for errormessages or should be truncated.
Overwrites an already existing chainable methodand provides access to the previous function orproperty. Must return functions to be used forname.
utils.overwriteChainableMethod(chai.Assertion.prototype,'lengthOf',function(_super){},function(_super){});
Can also be accessed directly fromchai.Assertion
.
chai.Assertion.overwriteChainableMethod('foo',fn,fn);
Then can be used as any other assertion.
expect(myFoo).to.have.lengthOf(3);expect(myFoo).to.have.lengthOf.above(3);
Overwrites an already existing method and providesaccess to previous function. Must return functionto be used for name.
utils.overwriteMethod(chai.Assertion.prototype,'equal',function(_super){returnfunction(str){varobj=utils.flag(this,'object');if(objinstanceofFoo){newchai.Assertion(obj.value).to.equal(str);}else{_super.apply(this,arguments);}}});
Can also be accessed directly fromchai.Assertion
.
chai.Assertion.overwriteMethod('foo',fn);
Then can be used as any other assertion.
expect(myFoo).to.equal('bar');
Overwrites an already existing property getter and providesaccess to previous value. Must return function to use as getter.
utils.overwriteProperty(chai.Assertion.prototype,'ok',function(_super){returnfunction(){varobj=utils.flag(this,'object');if(objinstanceofFoo){newchai.Assertion(obj.name).to.equal('bar');}else{_super.call(this);}}});
Can also be accessed directly fromchai.Assertion
.
chai.Assertion.overwriteProperty('foo',fn);
Then can be used as any other assertion.
expect(myFoo).to.be.ok;
Return a proxy of given object that throws an error when a non-existentproperty is read. By default, the root cause is assumed to be a misspelledproperty, and thus an attempt is made to offer a reasonable suggestion fromthe list of existing properties. However, if a nonChainableMethodName isprovided, then the root cause is instead a failure to invoke a non-chainablemethod prior to reading the non-existent property.
If proxies are unsupported or disabled via the user’s Chai config, thenreturn object without modification.
Test an object for expression.
Transfer all the flags forassertion
toobject
. IfincludeAll
is set tofalse
, then the base Chaiassertion flags (namelyobject
,ssfi
,lockSsfi
,andmessage
) will not be transferred.
varnewAssertion=newAssertion();utils.transferFlags(assertion,newAssertion);varanotherAssertion=newAssertion(myObj);utils.transferFlags(assertion,anotherAssertion,false);
Checks if two instances are compatible (strict equal).Returns false if errorLike is not an instance of Error, because instancescan only be compatible if they’re both error instances.
Checks if two constructors are compatible.This function can receive either an error constructor oran error instance as theerrorLike
argument.Constructors are compatible if they’re the same or if one isan instance of another.
Checks if an error’s message is compatible with a matcher (String or RegExp).If the message contains the String or passes the RegExp test,it is considered compatible.
Gets the constructor name for an Error instance or constructor itself.
Gets the error message from an error.Iferr
is a String itself, we return it.If the error has no message, we return an empty string.
Returns the name of a function.When a non-function instance is passed, returnsnull
.This also includes a polyfill function ifaFunc.name
is not defined.
Returns the name of a function.When a non-function instance is passed, returnsnull
.This also includes a polyfill function ifaFunc.name
is not defined.
This allows checking whether an object has ownor inherited from prototype chain named property.
Basically does the same thing as thein
operator but works properly with null/undefined valuesand other primitives.
varobj={arr:['a','b','c'],str:'Hello'}
The following would be the results.
hasProperty(obj,'str');// truehasProperty(obj,'constructor');// truehasProperty(obj,'bar');// falsehasProperty(obj.str,'length');// truehasProperty(obj.str,1);// truehasProperty(obj.str,5);// falsehasProperty(obj.arr,'length');// truehasProperty(obj.arr,2);// truehasProperty(obj.arr,3);// false
This allows the retrieval of property info in anobject given a string path.
The path info consists of an object with thefollowing properties:
path
undefined
This allows the retrieval of values in anobject given a string path.
varobj={prop1:{arr:['a','b','c'],str:'Hello'},prop2:{arr:[{nested:'Universe'}],str:'Hello again!'}}
The following would be the results.
getPathValue(obj,'prop1.str');// HellogetPathValue(obj,'prop1.att[2]');// bgetPathValue(obj,'prop2.arr[0].nested');// Universe