diff --git a/__test__/jest/jest.resetModules.test.cjs b/__test__/jest/jest.resetModules.test.cjs new file mode 100644 index 0000000..39d8675 --- /dev/null +++ b/__test__/jest/jest.resetModules.test.cjs @@ -0,0 +1,24 @@ +test('jest.resetModels', () => { + const a = require('c8') + a.foo = 'bar' + expect(a.foo).toBe('bar') + + const b = require('c8') + expect(a).toBe(b) + expect(b.foo).toBe('bar') + + jest.resetModules() + + const c = require('c8') + expect(c).not.toBe(a) + expect(c).not.toBe(b) + expect(c.foo).toBe(undefined) + + expect(a).toBe(b) + expect(b.foo).toBe('bar') + + const d = require('c8') + expect(d).not.toBe(a) + expect(d).not.toBe(b) + expect(d).toBe(c) +}) diff --git a/src/jest.js b/src/jest.js index 58fe097..d2ff770 100644 --- a/src/jest.js +++ b/src/jest.js @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import { describe as nodeDescribe, test as nodeTest, afterEach } from 'node:test' import { format, types } from 'node:util' import { jestfn, allMocks } from './jest.fn.js' -import { jestmock, requireActual, requireMock } from './jest.mock.js' +import { jestmock, requireActual, requireMock, resetModules } from './jest.mock.js' import * as jestTimers from './jest.timers.js' import './jest.snapshot.js' import { expect } from 'expect' @@ -67,6 +67,7 @@ const jest = { mock: jestmock, requireMock, requireActual, + resetModules, ...jestTimers, } diff --git a/src/jest.mock.js b/src/jest.mock.js index ba10ba8..062d4a0 100644 --- a/src/jest.mock.js +++ b/src/jest.mock.js @@ -25,6 +25,11 @@ export function requireMock(name) { return mapMocks.get(resolved) } +export function resetModules() { + // Caveat: only resets CJS modules, not ESM + for (const key of Object.keys(require.cache)) delete require.cache[key] +} + const isObject = (obj) => [Object.prototype, null].includes(Object.getPrototypeOf(obj)) function override(resolved, lax = false) {