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();
});
});
This error is due to not restoring the stub function properly. Use sandbox and then create the stub using the sandbox. After each test inside the suite, restore the sandbox
beforeEach(() => {
sandbox = sinon.createSandbox();
mockObj = sandbox.stub(testApp, 'getObj', fake_function)
});
afterEach(() => {
sandbox.restore();
});
For cases where you need to restore all the methods of one object, you can use the sinon.restore(obj)
.
Example:
before(() => {
userRepositoryMock = sinon.stub(userRepository);
});
after(() => {
sinon.restore(userRepository);
});
I was also hitting this using the before() and after() hooks of Mocha. I was also using the restore() as mentioned everywhere. Single test file ran fine, multiple did not. Finally found about Mocha root-level-hooks: I did not have my before() and after() inside my own describe(). So it finds all files with before() at the root-level and executes those before starting any tests.
So make sure you have a similar pattern:
describe('my own describe', () => {
before(() => {
// setup stub code here
sinon.stub(myObj, 'myFunc').callsFake(() => {
return 'bla';
});
});
after(() => {
myObj.myFunc.restore();
});
it('Do some testing now', () => {
expect(myObj.myFunc()).to.be.equal('bla');
});
});
For anyone running into this issue, if you stub or spy on the entire object, and you later do
sandbox.restore()
You'll still get the error. You have to stub/spy the individual methods.
I wasted forever trying to figure out what was wrong.
sinon-7.5.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With