Has been called with object assertion

iLemming picture iLemming · Jun 16, 2015 · Viewed 8.6k times · Source

Function I'm spying on, receives object as an argument. I need to assert that the function been called with certain properties of the object.

e.g: my SUT has:

function kaboom() {

    fn({ 
        foo: 'foo', 
        bar: 'bar', 
        zap: function() { ... },
        dap: true
     });
}

and in my test I can do this:

fnStub = sinon.stub();
kaboom();
expect(fnStub).to.have.been.called;

and that works (it's good to know that fn's been called). Now I need to make sure that the right object has been passed into the function. I care about only foo and bar properties, i.e. I have to set match for specific properties of the argument. How?

upd: sinon.match() seems to work for simple objects. Let's raise the bar, shall we?

What if I want to include zap function into assertion? How do I make that work?

Answer

Travis Kaufman picture Travis Kaufman · Jun 16, 2015

Assuming you're using sinon-chai, you can use calledWith along with sinon.match to achieve this

expect(fnStub).to.have.been.calledWith(sinon.match({
  foo: 'foo',
  bar: 'bar'
}));