JavaScript assertion function that allows sparse attributes and values
Most JavaScript assertion libraries allow you to compare if objects are equal, if they match or if one includes the other. But sometimes you don’t wont to compare in all the objects properties math or if all array items match. Say you want to test for the array of objects
when in fact you’re only interested only in
For example if using mjackson/expect library you can check for that by doing:
Asserting sparse attributes and values by using a placeholder
Our goal is to achieve testing by specifing which values can be anything as long as they are present:
You can see that we marked the payload
as a mandatory attribute which can have any value. That’s our placeholder. If we don’t care what the 2nd object should be then we can write the asserted
value as:
and it should pass the assertion.
Assertion function that allows sparse attributes and values
The whole code for the assertion is:
We define Any
(line 3) as a symbol so that it will be unique (a plain object would work as well). Then we use this symbol whenever we need the attribute to be present but don’t care about its value.
Then we use expectLooseEquality
(line 5) to make the assertion. It’s not the same syntax as expect
provides, but it uses its assert
method so it hooks nicely into the library.
This way you can save few lines of code and drastically improve tests readability.