Movatterモバイル変換


[0]ホーム

URL:


Plugin Utilities

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.

API Reference

.addChainableMethod(ctx, name, method, chainingBehavior)

  • @param{ Object }ctxobject to which the method is added
  • @param{ String }nameof method to add
  • @param{ Function }methodfunction to be used for `name`, when called
  • @param{ Function }chainingBehaviorfunction to be called every time the property is accessed

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

.addLengthGuard(fn, assertionName, isChainable)

  • @param{ Function }fn
  • @param{ String }assertionName
  • @param{ Boolean }isChainable

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 returnfnwithout 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.

.addMethod(ctx, name, method)

  • @param{ Object }ctxobject to which the method is added
  • @param{ String }nameof method to add
  • @param{ Function }methodfunction to be used for name

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

.addProperty(ctx, name, getter)

  • @param{ Object }ctxobject to which the property is added
  • @param{ String }nameof property to add
  • @param{ Function }getterfunction to be used for name

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;

.compareByInspect(mixed, mixed)

  • @param{ Mixed }firstelement to compare
  • @param{ Mixed }secondelement to compare

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.

.expectTypes(obj, types)

  • @param{ Mixed }objconstructed Assertion
  • @param{ Array }typeA list of allowed types for this assertion

Ensures that the object being tested against is of a valid type.

utils.expectTypes(this,['array','object','string']);

.flag(object, key, [value])

  • @param{ Object }objectconstructed Assertion
  • @param{ String }key
  • @param{ Mixed }value(optional)

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`

.getActual(object, [actual])

  • @param{ Object }object(constructed Assertion)
  • @param{ Arguments }chai.Assertion.prototype.assertarguments

Returns theactual value for an Assertion.

.getMessage(object, message, negateMessage)

  • @param{ Object }object(constructed Assertion)
  • @param{ Arguments }chai.Assertion.prototype.assertarguments

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 value

.getOperator(message)

  • @param{ Object }object(constructed Assertion)
  • @param{ Arguments }chai.Assertion.prototype.assertarguments

Extract 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.

.getOwnEnumerableProperties(object)

  • @param{ Object }object

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.

.getOwnEnumerablePropertySymbols(object)

  • @param{ Object }object

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.

.getProperties(object)

  • @param{ Object }object

This allows the retrieval of property names of an object, enumerable or not,inherited or not.

.inspect(obj, [showHidden], [depth], [colors])

  • @param{ Object }objThe object to print out.
  • @param{ Boolean }showHiddenFlag that shows hidden (not enumerable) properties of objects. Default is false.
  • @param{ Number }depthDepth in which to descend in object. Default is 2.
  • @param{ Boolean }colorsFlag to turn on ANSI escape codes to color the output. Default is false (no coloring).

Echoes the value of a value. Tries to print the value outin the best way possible given the different types.

.isProxyEnabled()

    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.

    .objDisplay(object)

    • @param{ Mixed }javascriptobject to inspect

    Determines if an object or an array matchescriteria to be inspected in-line for errormessages or should be truncated.

    .overwriteChainableMethod(ctx, name, method, chainingBehavior)

    • @param{ Object }ctxobject whose method / property is to be overwritten
    • @param{ String }nameof method / property to overwrite
    • @param{ Function }methodfunction that returns a function to be used for name
    • @param{ Function }chainingBehaviorfunction that returns a function to be used for property

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

    .overwriteMethod(ctx, name, fn)

    • @param{ Object }ctxobject whose method is to be overwritten
    • @param{ String }nameof method to overwrite
    • @param{ Function }methodfunction that returns a function to be used for name

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

    .overwriteProperty(ctx, name, fn)

    • @param{ Object }ctxobject whose property is to be overwritten
    • @param{ String }nameof property to overwrite
    • @param{ Function }getterfunction that returns a getter function to be used for name

    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;

    .proxify(object)

    • @param{ Object }obj
    • @param{ String }nonChainableMethodName

    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(object, expression)

    • @param{ Object }object(constructed Assertion)
    • @param{ Arguments }chai.Assertion.prototype.assertarguments

    Test an object for expression.

    .transferFlags(assertion, object, includeAll = true)

    • @param{ Assertion }assertionthe assertion to transfer the flags from
    • @param{ Object }objectthe object to transfer the flags to; usually a new assertion
    • @param{ Boolean }includeAll

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

    .compatibleInstance(thrown, errorLike)

    • @param{ Error }thrownerror
    • @param{ Error | ErrorConstructor }errorLikeobject to compare against

    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.

    .compatibleConstructor(thrown, errorLike)

    • @param{ Error }thrownerror
    • @param{ Error | ErrorConstructor }errorLikeobject to compare against

    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.

    .compatibleMessage(thrown, errMatcher)

    • @param{ Error }thrownerror
    • @param{ String | RegExp }errMatcherto look for into the message

    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.

    .getConstructorName(errorLike)

    • @param{ Error | ErrorConstructor }errorLike

    Gets the constructor name for an Error instance or constructor itself.

    .getMessage(errorLike)

    • @param{ Error | String }errorLike

    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.

    .getFuncName(constructorFn)

    • @param{ Function }funct

    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.

    .getFuncName(constructorFn)

    • @param{ Function }funct

    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.

    .hasProperty(object, name)

    • @param{ Object }object
    • @param{ String | Symbol }name

    This allows checking whether an object has ownor inherited from prototype chain named property.

    Basically does the same thing as theinoperator 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

    .getPathInfo(object, path)

    • @param{ Object }object
    • @param{ String }path

    This allows the retrieval of property info in anobject given a string path.

    The path info consists of an object with thefollowing properties:

    • parent - The parent object of the property referenced bypath
    • name - The name of the final property, a number if it was an array indexer
    • value - The value of the property, if it exists, otherwiseundefined
    • exists - Whether the property exists or not

    .getPathValue(object, path)

    • @param{ Object }object
    • @param{ String }path

    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

    [8]ページ先頭

    ©2009-2025 Movatter.jp