Search code examples
javascriptunit-testingsinonkarma-mochasinon-chai

How to check the number of arguments that a function has been called with Mocha, Chai and Sinon?


Lets say we have a service Foo which is exporting a function

function bar(x,y){
    console.log(x,y);
}

And we want to write a unit test which will test that this function is called with 2 arguments. I have tried this

var args = sandboxSinon.spy(Foo, 'bar').getCalls()[0].args;

And this is returning

undefined is not an object (evaluating 'sandboxSinon.spy(Foo, 'bar').getCalls()[0].args

Can someone figure out what is happening or how I could test it ?


Solution

  • Here's an example:

    const sinon = require('sinon');
    
    const Foo = {
      bar(x,y) {
        console.log(x, y);
      }
    };
    
    let spy = sinon.spy(Foo, 'bar');
    
    Foo.bar('hello', 'world');
    
    console.log( spy.firstCall.args.length ); // => 2