Has been called with object assertion

14.5k views Asked by At

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?

2

There are 2 answers

3
Travis Kaufman On

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'
}));
0
Nigrimmist On

To achieve called.with partial object check, you can also use chai-spies-augment package (https://www.npmjs.com/package/chai-spies-augment) :

Usage (please, notice to .default after importing):

const chaiSpies = require('chai-spies');
const chaiSpiesAugment = require('chai-spies-augment').default;

chai.use(chaiSpies);
chai.use(chaiSpiesAugment);

usage :

const myStub = { myFunc: () => true };
const spy1 = chai.spy.on(myStub, 'myFunc');
myStub.myFunc({ a: 1, b: 2 });

expect(spy1).to.have.been.called.with.objectContaining({ a: 1 });