Search code examples
javascriptnode.jssinon

How to match an array of objects with sinon.js?


How can I match an array of results in a sinon matcher?

For example, how can this code work?

var mystub = sinon.stub();
var myarg = { val: 1, mylist: [ {a:1}, {b:2}, {c:3,d:4} ] };

mystub(myarg);

sinon.assert.calledOnce(mystub).withArgs(
  sinon.match({val: 1, mylist: [{a:1},{b:2},{c:3,d:4}]}) // this doesn't work
);

How can I get this to work? (Note that in my test, I don't have access to myarg - so I need to match it).

Obviously, I could write a custom function matcher, but I'm looking for something a bit easier to read and write.


Solution

  • The custom matching function in the accepted answer is useful to know about but total overkill for this simple use case. To build on the useful answer from Eryk Warren, how about this:

    // match each element of the actual array against the corresponding entry in the expected array
    sinon.assert.match(actual, expected.map(sinon.match));