mardi 2 août 2016

Sinon - multiple stub levels

If I try to stub a function several times, I get

TypeError: Attempted to wrap get which is already wrapped

How can I get stub to work when I have several levels of test wrapping, like:

describe('Some core feature', function () {
  beforeEach(function () {
    const originalMethod = HTTP.get;
    sinon.stub(HTTP, 'get', (route, options) => {
      if (route.indexOf('localhost') === -1) {
        // prevent tests from altering external service
        return {};
      }
      return originalMethod(route, options);
    }
  });

  afterEach(function () {
    HTTP.get.restore();
  });

  it('works for big feature Y', function() {
    except(HTTP.get('localhost')).to.eq(whatEverThisIsInProdMode);
    except(HTTP.get('somedomain.com').data).to.be.undefined;
    except(HTTP.get('someotherdomain.com').data).to.be.undefined;
  });



  describe('Some minor feature', function () {
    beforeEach(function () {
      const _method = HTTP.get;
      // The following fails because I'm stubing a stub
      sinon.stub(HTTP, 'get', (route, options) => {
        if (route.indexOf('somedomain.com') !== -1) {
          // mock some 3rd party api
          return {
            data: 123
          };
        }
        return _method(route, options);
      }
    });

    afterEach(function () {
      HTTP.get.restore();
    });

    it('works for small feature X', function() {
      except(HTTP.get('localhost')).to.eq(whatEverThisIsInProdMode);
      except(HTTP.get('somedomain.com').data).to.eq(123);
      except(HTTP.get('someotherdomain.com').data).to.be.undefined;
    });
  });
});

Aucun commentaire:

Enregistrer un commentaire