expect.addAssertion([typeName, ...], [pattern, ...], handler)
Signature:
New assertions can be added to Unexpected to following way.
The above assertion definition makes the following expects possible:
Let's dissect the different parts of the custom assertion we just introduced.
The first parameter to addAssertion
is a string or an array
specifying which types the assertion should be defined on. In this
case the assertion in only defined for arrays. In case the type is not
specified the assertion will be defined for the type any
, and would
be applicable any type. See the Extending Unexpected with new types
section for more information about the type system in Unexpected.
The second parameter to addAssertion
is a string or an array stating
the patterns this assertion should match. A pattern has the following
syntax. A word in square brackets represents a flag that can either be
there or not. If the flag is present this.flags[flag]
will contain
the value true
. In this case not
is a flag. When a flag it present
in a nested expect
it will be inserted if the flag is present;
otherwise it will be removed. Text that is in parentheses with
vertical bars between them are treated as alternative texts that can
be used. In this case you can write ordered as an alternative to
sorted.
The last parameter to addAssertion
is function that will be called
when expect
is invoked with an expectation matching the type and
pattern of the assertion.
So in this case, when expect
is called the following way:
The handler to our assertion will be called with the values the following way, where the not flag in the nested expect will be removed:
Controlling the output of nested expects
When a call to expect
fails inside your assertion the standard error
message for the custom assertion will be used. In the case of our
sorted assertion fails, the output will be:
We can control the output of the nested expects by changing the
this.errorMode
property.
If we change the error mode to bubble, we get the following output:
If we change the error mode to nested, we get the following output:
The best resource for learning more about custom assertions is to look at how the predefined assertions are built: