lundi 30 novembre 2020

Stubbing method using sinon

I am trying to stub a method in sinon.

Here is a simplified example

function a() {
    return b().add(1, 'days);
}

function b() {
   return moment.utc();
}

module.exports = {
  a: a,
  b: b
};

I want to stub function b() to return a specific moment date when called from a file that has required it (e.g. theFile.b()) AND it should also be mocked internally when method a() is called.

I have tried the following

  sinon.stub(theFile, 'b').callsFake(function() {
    console.log("Calling mocked sinon ")
    return moment("2021-10-10", 'YYYY-MM-DD').utc().startOf('day');
  });

Which works when called externally but not when called internally in function a().

I can see this is because sinon is overriding the module export but there must be a way around this. could anyone help?

Aucun commentaire:

Enregistrer un commentaire