Has been called with object assertion
Asked Answered
K

2

20

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?

Katiakatie answered 15/6, 2015 at 22:25 Comment(0)
S
37

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'
}));
Street answered 16/6, 2015 at 18:49 Comment(4)
but that for some reason didn't work for me, it would say that the rest properties don't match. let me try again, maybe I'm doing something wrong hereKatiakatie
what's the exact error message you're getting? Is it saying the function's not being called at all, or does it say it's being called with the wrong arguments?Street
Oh actually I found what wasn't working. sinon.match with an object that has a property of a function. That's not working. something like sinon.match({ foo: sinon.stub() }) can't find a way to make that workKatiakatie
@Katiakatie 9yrs later, see Custom Matchers in sinonjs.org/releases/latest/matchersWinslow
M
3

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 });
Makhachkala answered 19/11, 2019 at 18:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.