Henry
Henry

Reputation: 145

Mocha sinon.spy always showing function call 0 times

I am new to mocha/chai. I am trying to write the unit test case for following scenario. I want to test whether "callchildfunc" and "childfunc2" is called or not upon calling "parent()" function.

I have read the fundamental and what I understood is if you are spying on any function then just put assert on that function to check if that function is called or not. Means in above script file If i will spy on "childfunc2" and "callchildfunc" function then I don't need to call here in test file since it is already called in script file under parent function. Please correct my understanding if I am wrong.

This is my script.js file

// script.js    

function childfunc2(){
    console.log("child function without return");
}
function callchildfunc(var1, var2){
   return var1 + var2;
}
function parent(x){
   var getreturnval = callchildfunc(x, 1);
   console.log(getreturnval);
   childfunc2();
}

This is my test file.

//scenario 1

describe('Test for parent() function ', function(){
   it('should make parent call ', function(){

        var spy1 = sinon.spy(window, 'callchildfunc');
        var spy2 = sinon.spy(window, 'childfunc2');
        parent(2);
        expect(spy1).to.have.been.called();
        expect(spy2).to.have.been.called();
        // or
        sinon.assert.calledOnce(spy1);
        sinon.assert.calledOnce(spy1);

    });
});

After running the test always I am getting this error.

AssertError: expected childfunc2 to be called once but was called 0 times

Also If I change the test file and call the spy function then it will work.

var spy1 = sinon.spy(window, 'callchildfunc');
var spy2 = sinon.spy(window, 'childfunc2');
parent(2);
// After addding these below 2 lines.
window.childfunc2();
window.callchildfunc();

Any help?

Upvotes: 2

Views: 1846

Answers (1)

user2347763
user2347763

Reputation: 489

// Script.js 

module.exports= {
childfunc2:function(){
    console.log("child function without return");
},
callchildfunc:function(var1, var2){
   return var1 + var2;
},
parent:function(x){
   var getreturnval = this.callchildfunc(x, 1);
   console.log(getreturnval);
   this.childfunc2();
}
};

// Test.js

var sinon= require('sinon'), expect=require('chai').expect
var r= require('./functests')
describe('Test for parent() function ', function(){
   it('should make parent call ', function(){
        var spy1 = sinon.spy(r, 'callchildfunc');
        var spy2 = sinon.spy(r, 'childfunc2');
        r.parent(2);
//        expect(spy1).to.have.been.called();
  //      expect(spy2).to.have.been.called();
        // or
        sinon.assert.calledOnce(spy1);
        sinon.assert.calledOnce(spy1);

    });
});

// Screenshot

enter image description here

Upvotes: 2

Related Questions