testdouble.js

Custom argument matchers

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.

Example

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

td.matchers.create API

The create function takes a configuration object with the following properties

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