Jest: Requiring modules with isolateModules does not work if module has already been required with a non-isolated method e.g: using require.

Created on 11 Feb 2019  路  4Comments  路  Source: facebook/jest

馃悰 Bug Report

Requiring modules with isolateModules does not work if module has already been required with a non-isolated method e.g: using require.

To Reproduce

describe('Isolated modules test', () => {
  test('should be able to return different isolated modules', () => {
    let m0 = require('../path/to/testing/module')
    // let m0
    // jest.isolateModules(() => {
    //   m0 = require('../path/to/testing/module')
    // })

    let m1
    jest.isolateModules(() => {
      m1 = require('../path/to/testing/module')
    })

    expect(m1).toStrictEqual(m0) // does not fail, while it should.
  })
})

Expected behavior

Requiring a module should not have an affect to an isolated module registry.

describe('Isolated modules test', () => {
  test('should be able to return different isolated modules', () => {
    let m0 = require('../path/to/testing/module')
    // let m0
    // jest.isolateModules(() => {
    //   m0 = require('../path/to/testing/module')
    // })

    let m1
    jest.isolateModules(() => {
      m1 = require('../path/to/testing/module')
    })

    expect(m1).toStrictEqual(m0) // should fail.
  })
})

Run npx envinfo --preset jest

npx: installed 1 in 2.159s

  System:
    OS: macOS 10.14.1
    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
  Binaries:
    Node: 8.15.0 - ~/.nvm/versions/node/v8.15.0/bin/node
    Yarn: 1.9.4 - ~/.yarn/bin/yarn
    npm: 6.4.1 - ~/.nvm/versions/node/v8.15.0/bin/npm
  npmPackages:
    jest: ^24.1.0 => 24.1.0
Bug

Most helpful comment

I also ran into this. My use case is:

const thing = require('../thing');

describe('thing', () => {
   // many tests involving thing
   // ...

    test('some special case', () => {
      jest.isolateModules(() => {
        jest.mock('some-module-that-thing-interacts-with', ...);

        thing = require('../thing');
        // some assertion involving thing
      });
    });
});

All 4 comments

@rogeliog mind taking a look at this?

I also ran into this. My use case is:

const thing = require('../thing');

describe('thing', () => {
   // many tests involving thing
   // ...

    test('some special case', () => {
      jest.isolateModules(() => {
        jest.mock('some-module-that-thing-interacts-with', ...);

        thing = require('../thing');
        // some assertion involving thing
      });
    });
});

I think this should at least be documented since the docs actually show a second import outside the isolatedModules:

let myModule;
jest.isolateModules(() => {
  myModule = require('myModule');
});

const otherCopyOfMyModule = require('myModule');

Any progress on this issue?

Was this page helpful?
0 / 5 - 0 ratings