Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way of using sinon spy restore or reset?

I have a test suit with mocha, sinon and chai:

describe('general visor methods tests', () => {

    let res, req, next, resSpy, resNext;

    beforeEach(() => {
        res = {};
        next = () => {};
        resSpy = res.json = sinon.spy();
        resNext = next = sinon.spy();
    });
    afterEach(() => {
        resSpy.restore();
        resNext.reset();
    });


describe('get basemap layers from owner model', () => {
    it('should send the basemap provided by the owner model', () => {
        owner.basemap = ['basemap1', 'basemap2'];
        getBaseMapLayersFromConfig(req, res, next);
        //  console.log(resSpy.args[0][0].data);
        expect(resSpy.calledOnce).to.eql(true);
        expect(resSpy.args[0][0].message).to.eql('basemaps correctly found');
        expect(resSpy.args[0][0].data).to.eql(['basemap1', 'basemap2']);
    });

...

if I put resSpy.reset() it works fine. I've read that the reset() function is to reset the state of the spy.

But what i don't understand is that if i put resSpy.restore() then it thows the next error:

TypeError: resSpy.restore is not a function

I don't know what I'm doing wrong or what should be the correct way of using restore.

Also I don't quite know when should i use reset or restore.

like image 332
sendra Avatar asked Aug 31 '16 08:08

sendra


1 Answers

spy.restore() is only useful if you're using the following initialization:

let someSpy = sinon.spy(obj, 'someFunction');

This will replace obj.someFunction with the spy. If you ever want to go back to the original, you use someSpy.restore().

You're using a standalone spy, so there's nothing to restore.

Also, because you're creating new spies for each test, in beforeEach, you don't have to reset anything in afterEach. That's only useful if you want to reuse the spies:

describe('general visor methods tests', () => {
  let someSpy = sinon.spy(); // create the spy once

  afterEach(() => {
    someSpy.reset(); // reset after each test
  });

  ...
});
like image 185
robertklep Avatar answered Sep 20 '22 06:09

robertklep