Jest: require.cache always be {} in one module?

Created on 7 Mar 2018  路  1Comment  路  Source: facebook/jest

A bug?

here is load-uncached.js

module.exports = module => {
  let moduleExport
  try {
    const modulePath = require.resolve(module)
    for (let key in require.cache) {
      delete require.cache[key]
    }
    moduleExport = require(modulePath)
  } catch (err) {
    ....
  }

  return moduleExport
}

here is load-uncached.test.js:

jest.mock('args', () => ({}))

require('./router')  // add  router module to require.cache
const loadUncached = require('load-uncached')

describe('test load-uncached', () => {
  afterAll(() => {
    jest.resetModules()
  })

  it('should throw error when mock config file does not exist', () => {
    expect(() => loadUncached('xxx')).toThrow(/xxx/)
  })

  it('should require uncached module', () => {
    const moduleExport = loadUncached('../src/args')
    expect(moduleExport).toEqual({})
  })
})

What is the current behavior?

it seems that require.cache always be {} in load-uncached.js.

What is the expected behavior?

require.cache in load-uncached.js should be {router: ...} when require('router') in load-uncached.test.js.

my jest configuration in package.json:

"jest": {
    "verbose": true,
    "notify": true,
    "testEnvironment": "node",
    "collectCoverage": true,
    "roots": [
      "<rootDir>/__tests__"
    ],
    "modulePaths": [
      "<rootDir>/src"
    ],
    "moduleDirectories": [
      "<rootDir>/__mocks__",
      "node_modules"
    ],
    "coverageReporters": [
      "html",
      "text",
      "text-summary"
    ]
  }

jest: v22.4.2
npm: v5.5.1
node: v9.3.0
os: v10.12.3

Most helpful comment

Jest does not implement require.cache, it's always just {} - it has its own cache. Use jest.resetModules() to clear it

>All comments

Jest does not implement require.cache, it's always just {} - it has its own cache. Use jest.resetModules() to clear it

Was this page helpful?
0 / 5 - 0 ratings