POST POST

SEP
29
2017

Creating a Custom Matcher for TS-Mokito

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import * as _ from 'lodash';
import { Matcher } from 'ts-mockito/lib/matcher/type/Matcher';
export class ArrayMatcher extends Matcher {
private value: any;
constructor(private expected) {
super();
}
match(value: any): boolean {
return _.isEqual(this.expected, value);
}
toString(): string {
return `Did not match ${this.expected}`;
}
}

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
2
3
export function arrayMatches(expected): any {
return new ArrayMatcher(expected);
}

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.


Simon Timms

Email Email
Web Web
Twitter Twitter
GitHub GitHub
RSS

Looking for someone else?

You can find the rest of the Western Devs Crew here.

© 2015 Western Devs. All Rights Reserved. Design by Karen Chudobiak, Graphic Designer