In addition to the built-in argument matchers described along with stubbing, it’s easy to define custom argument matchers to meet your specific needs as well.
There’s nothing magical about matchers. Any object passed into a when() or
verify() invocation that has a __matches function on it and returns truthy
when it matches and falsey when it doesn’t is considered a matcher by
testdouble.js. That said, we provide a td.matchers.create() helper for creating
your own custom matchers in a way that’ll help ensure your users will get better
messages from td.explain calls and td.verify failures.
(For the record, arguments without a __matches property will only match an
actual invocation if it passes lodash’s deep
_.isEqual test.)
The examples in this document assume you’ve aliased testdouble to td.
Here’s a naive implementation of a matcher named isA which will check whether
the expected type of an argument matches the type of the argument actually passed
to the test double function from the subject under test.
isA = td.matchers.create({
  name: 'isA',
  matches: function(matcherArgs, actual) {
    var expected = matcherArgs[0]
    return actual instanceof expected
  }
})
Once defined, the above function can be used in a test like this:
var datePicker = td.function()
td.when(datePicker(isA(Date))).thenReturn('good')
datePicker(new Date()) // 'good'
datePicker(5) // undefined
The create function takes a configuration object with the following properties
actual argument satisfies the matcher’s rules, given what the user
passed to the matcher as matcherArgs when setting it up. For instance, if
td.when(func(isFooBar('foo','bar')).thenReturn('baz') is configured, then
func('biz') is invoked, then isFooBar’s matches function will be invoked
with matcherArgs of ['foo','bar'] and actual of 'biz'matcherArgs and should return a
string nametd.callback functionality of the library depends on this optiontd.when is satisfied (e.g. all arguments of an invocation match the
arguments & matchers of the stubbing) or td.verify is satisfied (e.g. one or
more invocations match the given arguments & matchers). This is useful when a
matcher’s behavior depends on whether actual invocations matched the test’s
expectations (as is the case with argument
captors)For some examples of td.matchers.create() in action, check out the
built-in matchers provided by testdouble.js.
Previous: Replacing Real Dependencies with Test Doubles Next: Debugging with testdouble.js