Jest has the ability to check for partial matches on arrays and objects. Let us see how to do partial matching in Jest.
expect has powerful matcher methods for partial matching, and they can also be combined with the
Matching objects partially using
When trying only to match a subset of an object’s properties, we can use the
The above test will pass if the name attribute matches in the test. The other key-value pairs in the object have no relevance to the outcome of the test.
The above test could have been easily rewritten as:
But partial matching in Jest shines when multiple properties need to be tested. For example:
Is more readable and maintainable than
There is only one assert statement with the partial matching statement, and all related properties are tested in it.
Partial matching on nested objects
objectContaining matcher can also be used to match nested objects.
As long as the author name matches, the above test will always pass.
Matching arrays partially using
Similarly, if we only care about matching partial values in an array, we can use
The above test passes as long as one of the entries in the given array is wisdomgeek.
It is also worth mentioning that
arrayContaining works irrespective of the order of the array.
This can then be used to check that the array does have all the elements that it should have and not in any particular order. If we wanted to check that it had only the items that we wanted it to have and nothing else, we could add an additional length check as well.
Combining object and array partial matching
We can combine the above two matchers to create various permutations and combinations if we wanted to do some advanced checks.
Partial match with toHaveBeenCalledWith arguments
These matchers can even be combined with Jest’s toHaveBeenCalledWith function. Using the combination of toHaveBeenCalledWith and partial, Jest tests can assert that a function was called with a particular argument.
And that is all, folks. I hope that this post helps you with writing some advanced test cases using partial matching. If you have any questions, do let us know in the comments.