node.jssinon

Sinon error Attempted to wrap function which is already wrapped


Though there is a same question here but I could not find answer to my problem so here goes my question:

I am testing my node js app using mocha and chai. I am using sinion to wrap my function.

describe('App Functions', function(){

  let mockObj = sinon.stub(testApp, 'getObj', (dbUrl) => {
     //some stuff
  });
  it('get results',function(done) {
     testApp.someFun
  });
}

describe('App Errors', function(){

  let mockObj = sinon.stub(testApp, 'getObj', (dbUrl) => {
     //some stuff
  });
  it('throws errors',function(done) {
     testApp.someFun
  });
}

When I try to run this test it gives me error

Attempted to wrap getObj which is already wrapped

I also tried putting

beforeEach(function () {
  sandbox = sinon.sandbox.create();
});

afterEach(function () {
  sandbox.restore();
});

in each describe, but still giving me same error.


Solution

  • You should restore the getObj in after() function, please try it as below.

    describe('App Functions', function(){
        var mockObj;
        before(function () {
                mockObj = sinon.stub(testApp, 'getObj', () => {
                     console.log('this is sinon test 1111');
                });
        });
    
        after(function () {
            testApp.getObj.restore(); // Unwraps the spy
        });
    
        it('get results',function(done) {
            testApp.getObj();
        });
    });
    
    describe('App Errors', function(){
        var mockObj;
        before(function () {
                mockObj = sinon.stub(testApp, 'getObj', () => {
                     console.log('this is sinon test 1111');
                });
        });
    
        after( function () {
            testApp.getObj.restore(); // Unwraps the spy
        });
    
        it('throws errors',function(done) {
             testApp.getObj();
        });
    });
    

    Update 2022/01/22

    Using sinon's sanbox you could created stub mocks with sandbox.stub() and restores all fakes created through sandbox.restore(), Arjun Malik give an good example