Writing Custom Assertions for NightwatchJS
Ever felt limited by the assertions available in NightwatchJS? You can write your own!
SEO is a big factor for our business and our page titles change a lot. This makes acceptance testing difficult, because it will result in false negatives and/or unnecessary maintenance.
We write acceptance tests for our frontend using NightwatchJS. The .title assertion only accepts a string and it needs to be exactly equal to the page title. What we need is for that assertion to accept a Regex, because certain keywords will almost always be present in the page title.
TL;DR: the assertion code!
Let's break it down. A custom assertion extends the .assert
and .verify
namespaces: in this case we add it to the assertion
namespace, as you can see in the last line of the code above.
The actual custom assertion has a pretty straightforward interface:
It accepts a string
as this.message
, which is shown in your console while debugging. A bit like this:
In this.command
, we execute some code and the result is passed to this.value
. In this case, the result of this.command
is the page title, so we don't want to do anything other than just pass the result to this.pass
for the actual assertion.
In this.pass
, the actual assertion takes place: the value
that the function receives is tested against the regular expression and it returns true
or false
. If the value
does not contain the expected expression
, then the message will be shown like this:
In this.expected
, you write what you expect the result to be: in this case, we expect the result to be true
. If this.pass
would have returned something different, let's say a string, then this piece of code should contain the expected string.
To enable your new custom assertion, you need to link to it in your nightwatch configuration. I found the documentation on this a bit lacking, but it boils down to adding custom_assertions_path: 'path/to/my/assertions'
in your nightwatch.json (configuration) file.
That's it! In your tests you can now write .assert.checkTitle(/Part of the page title/)
. If you have any questions, please leave a comment below!