Skip to content

Commit

Permalink
feat: support jest.resetModules for CJS modules
Browse files Browse the repository at this point in the history
  • Loading branch information
ChALkeR committed Jul 10, 2024
1 parent fb3d957 commit 947db4b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
24 changes: 24 additions & 0 deletions __test__/jest/jest.resetModules.test.cjs
Original file line number Diff line number Diff line change
@@ -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)
})
3 changes: 2 additions & 1 deletion src/jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -67,6 +67,7 @@ const jest = {
mock: jestmock,
requireMock,
requireActual,
resetModules,
...jestTimers,
}

Expand Down
5 changes: 5 additions & 0 deletions src/jest.mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 947db4b

Please sign in to comment.