Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SinonJS: calledWith() with exact object

I am trying to test that a spy in my Sinon tests is being called with an exact object: no missing properties, no additional properties and no changed properties.

I have this:

assert( viewer.entities.add.calledWith( completeEntityObject ) );

but if I omit some properties from completeEntityObject, the test succeeds. I would like it to fail. I would like a deep comparison.

I have tried looking at the sinon.match methods but, although there are tests for arrays being deeply equal, there is no such test for objects. How can I accomplish this?

like image 991
serlingpa Avatar asked Jan 05 '18 17:01

serlingpa


1 Answers

For anyone looking for how to assert that your sinon spy was called with certain arguments, here's a simple example.

  const spy = sinon.spy();

  // If spy is ever called in your code with some arguments, like so:
  spy({ hello: 'world'});

  // You can assert for it in your tests like this:
  expect(spy.getCall(0).calledWith(sinon.match({ hello: 'world' }))).to.be.true;

  // Breaking this down a bit:
  // spy.getCall(0) gives us the first time our spy function was called (because it can be called more than once)

  // Bonus: While debugging, you can use spy.getCalls()[0].args[0] to get the arguments that your spy function was called with.

I hope this is helpful - this is my first SO reply so forgive me if I break rules, or haven't explained things in detail.

like image 173
nkhil Avatar answered Nov 10 '22 00:11

nkhil