theKashey / rewiremock

The right way to mock dependencies in Node.js or webpack environment.
MIT License
492 stars 30 forks source link

ForceCacheClear doesn't remove overrides #122

Open kataik opened 4 years ago

kataik commented 4 years ago

Sorry in advance if I misunderstood the concept.

I have the following module dependencies:

A -> B B -> C

I have unit tests for module A and B (executed in this order by mocha). In A's tests I use rewiremock to mock B and in B's unit tests I mock C the same way. Before running tests for B, I call forceCacheClear(false/true/'nocache') to restore B so I am able to require the original B module between rewiremock.enable() and rewiremock.disable() calls.

My issue is that whatever I do, B is resolved to the already mocked version of it when it gets executed after A's unit tests.

A simplified example (module main's default function originally returns 'foo'):

  rewiremock(() => require('./main')).withDefault(() => 'bar');
  rewiremock.enable();
  console.info(require('./main').default()); // bar
  rewiremock.disable();
  console.info(require('./main').default()); // foo
  rewiremock.enable();
  console.info(require('./main').default()); // bar
  rewiremock.disable();
  rewiremock.forceCacheClear(false);
  rewiremock.enable();
  console.info(require('./main').default()); // bar
  rewiremock.disable();
  console.info(require('./main').default()); // foo
  rewiremock.enable();
  console.info(require('./main').default()); //bar
  rewiremock.disable();
  rewiremock.forceCacheClear(true);
  rewiremock.enable();
  console.info(require('./main').default()); // bar
  rewiremock.disable();
  console.info(require('./main').default()); // foo
  rewiremock.enable();
  console.info(require('./main').default()); // bar
  rewiremock.disable();
  rewiremock.forceCacheClear('nocache');
  rewiremock.enable();
  console.info(require('./main').default()); // bar
  rewiremock.disable();
  console.info(require('./main').default()); // foo
  rewiremock.enable();
  console.info(require('./main').default()); // bar
  rewiremock.disable();

Btw, directly deleting the require cache also has no effect.

Can you please point me the right direction on how to isolate my mock states for my unit tests? Any help is greatly appreciated.

theKashey commented 4 years ago

Btw, directly deleting the require cache also has no effect.

Sounds like you need to "cancel" the first line of your example.

I call forceCacheClear(false/true/'nocache') to restore B

no, forceCacheClear is only about different modes to handle cache, while you have to cancel mocking. Probably you need