2016-03-18 7 views
19

Anche se v'è una stessa domanda qui, ma non sono riuscito a trovare risposta al mio problema quindi ecco qui la mia domanda:errore Sinon è tentato di avvolgere la funzione che è già avvolto

sto testando un'applicazione mio nodo js utilizzando moka e chai . Sto usando sinion per avvolgere la mia funzione.

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 
    }); 
} 

Quando si tenta di eseguire questo test mi dà errore

Attempted to wrap getDbObj which is already wrapped 

Ho anche provato a mettere

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

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

in ogni descrivere, ma ancora mi dà lo stesso errore.

risposta

31

È necessario ripristinare la funzione getObj nella funzione after(), provare come di seguito.

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(); 
    }); 
}); 
+0

ringraziamento che ha funzionato. –

+0

Dopo aver provato il metodo sopra accettato, ricevo lo stesso errore sotto "prima di tutto", gancio –

+0

@AshwinHegde, potresti darmi i tuoi codici di prova? Forse posso trovare qualche problema qui. – zangw

5

Per i casi in cui è necessario ripristinare tutti i metodi di un oggetto, è possibile utilizzare il sinon.restore(obj).

Esempio:

before(() => { 
    userRepositoryMock = sinon.stub(userRepository); 
}); 

after(() => { 
    sinon.restore(userRepository); 
}); 
+0

Questo non ha funzionato per me quando si esegue lo stub delle funzioni sull'oggetto. Ho dovuto ripristinare per funzione come la risposta accettata mostra. –

+0

sinon.restore() è stato deprecato in Sinon v2 e rimosso in seguito. '// In precedenza sinon.restore (stubObject); // Typescript (stubObject as any) .restore(); // Javascript stubObject.restore(); ' – MatthiasSommer

Problemi correlati