theKashey/rewiremock

ForceCacheClear doesn't remove overrides

kataik opened this issue · 1 comments

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.

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

  • rewiremock.clear(). It just clears everything
  • inScope helpers (rewiremock.proxy included), which does not affect anything around them
  • and it seems to me that you import rewiremock in a wrong way - it is expected to "autoclear" itself from the cache, if imported directly, or if overrideEntryPoint is in use