title | weight | render-file |
---|---|---|
Composing an Assertion |
30 |
false |
Before we begin adding methods and properties to the language chain, we should first examine how to invoke an assertion, and the expected behavior should it fail.
For this, each constructed Assertion
has a method called simply assert
. It accepts
many parameters and its behavior can change depending on whether an assertion was
negated or not.
To begin, we will construct Arthur again, then we can assert that he is who he says he is.
var arthur = new Assertion('Arthur Dent');
arthur.assert(
arthur._obj === 'Arthur Dent'
, "expected #{this} to be 'Arthur Dent'"
, "expected #{this} to not be 'Arthur Dent'"
);
Chai will check the first argument; if it is true
then the assertion passed, but if it is false
the assertion failed and the first error message will be thrown as part of a chai.AssertionError
.
Conversely, if the language chain was negated, it will consider false
a pass and true
a failure.
The second error message will be included in the thrown error instead.
In all, the assert
method accepts six arguments:
- a boolean (result of a truth test)
- a string error message to be used if the first argument is
false
- a string error message to be used if the assertion is negated and the first argument is
true
- (optional) the expected value
- (optional) the actual value, which will default to
_obj
- (optional) a boolean which indicates whether to display a diff in addition to the message if the first argument is
false
As you can see from the above example, Chai can accept template tags to dynamically compose the error message. When used, these template tags will be replaced with a stringified replacement of the object in question. There are three template tags available.
#{this}
: the_obj
of the assertion#{exp}
: the expected value, if it was provided inassert
#{act}
: the actual value, defaults to_obj
but can be overwritten by value provided inassert