For better or worse I've been working with a lot of Angular as of late. One of the better tools I've found for helping out with testing is a great little mocking library called ts-mokito. I don't want to get into why I still like to have a mocking library even with a language like JavaScript - that's another post.
Testing today I ran into an annoying problem in that I was testing an angular route like so
1 | verify(mockRouter.navigate(['/some/route'])).called(); |
This test was always failing. This is because the argument to navigate is an array and in JavaScript
1 | ['/some/route'] !== ['/some/route'] |
How unfortunate. Fortunately there isn't much to a custom matcher in ts-mokito. You can already do
1 | verify(mockRouter.navigate(anything())).called(); |
To simply check that something was passed in but we'd like our tests to be a bit more robust than that. Enter the ArraryMatcher
1 | import * as _ from 'lodash'; |
As you can see it has an implementation of the match
function which uses the isEqual
from lodash. This class can be substituted into our verify
1 | verify(mockRouter.navigate(<any>new ArrayMatcher(['/some/route'])).called(); |
That's a bit ugly with casting in there. This can be fixed by exporting a function from the ArrayMatcher
1 | export function arrayMatches(expected): any { |
Which allows for the much more pleasant syntax
1 | verify(mockRouter.navigate(arrayMatches([`/some/route`]))).called(); |
Easily done and it should be simple to implement any other sort of matcher you like.