how to reset module imported between tests

@ltamajs solution is great for require but in the case you are using import then you will receive the next error.

SyntaxError: /path/to/test/file.js: 'import' and 'export' may only appear at the top level

To solve this issue, you can use the babel-plugin-dynamic-import-node plugin and then reset the modules. Overall, it looks like this:

describe('MyTests', () => {
  let MyModule;

  beforeEach(() => {
    return import('../module/path').then(module => {
      MyModule = module;
      jest.resetModules();
    });
  });

  test('should test my module', () => {
    expect(MyModule.aMethod).not.toBeUndefined();
  });
});

Source: https://github.com/facebook/jest/issues/3236#issuecomment-698271251


You have to re-import or re-require your module. Check the doc or this issue for more information:

https://github.com/facebook/jest/issues/3236

https://facebook.github.io/jest/docs/en/jest-object.html#jestresetmodules

describe('MyModule', () => {
    beforeEach(() => {
        jest.resetModules()
    });

    describe('init', () => {
        const myModule = require('./MyModule');

        it('not throws exception when called', () => {
            expect(() => myModule.init()).not.toThrow();
        });
    })
    describe('do', () => {
        const myModule = require('./MyModule');

        it('throw when not init', () => {
            expect(() => myModule.do()).toThrow();
        });
    })
})