FormidableLabs / jest-next-dynamic

Resolve Next.js dynamic import components in Jest tests
MIT License
69 stars 7 forks source link

Not compatible with Jest's resetMocks option #19

Open josselinbuils opened 3 years ago

josselinbuils commented 3 years ago

Hello,

First thank you for this great lib 😄

It seems that the way to use this library described in the documentation is not compatible with the resetMocks option of Jest.

Indeed, next/dynamic is only mocked for the first test and the real one is restored from the second test.

I don't know if it could be managed by the lib directly but it could be at least documented.

Regards, Josselin BUILS

josselinbuils commented 3 years ago

Here is a possible but quite verbose workaround:

  let MyComponent;

  beforeAll(async () => {
    let preloadAll;
    jest.isolateModules(() => {
      preloadAll = require('jest-next-dynamic');
    });
    MyComponent = require('../MyComponent').default;
    await preloadAll();
  });
josselinbuils commented 3 years ago

I don't understand why it is working but putting this in a file referenced by setupFilesAfterEnv in the Jest config seems also to fix the issue:

jest.isolateModules(() => {
  const preloadAll = require('jest-next-dynamic');

  beforeEach(async () => {
    await preloadAll();
  });
});

The unknown thing to me is why the mock implementation is not reset between tests in these conditions as this setup file seems to be executed only once by test file.