Skip to content

Commit

Permalink
feat: add support unstable_unmockModule (#15080)
Browse files Browse the repository at this point in the history
  • Loading branch information
BondarenkoAlex committed Jun 30, 2024
1 parent d65d4cc commit 9c9ce8a
Show file tree
Hide file tree
Showing 9 changed files with 140 additions and 21 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
- `[jest-runtime]` Support `import.meta.filename` and `import.meta.dirname` (available from [Node 20.11](https://nodejs.org/en/blog/release/v20.11.0)) ([#14854](https://github.com/jestjs/jest/pull/14854))
- `[jest-runtime]` Support `import.meta.resolve` ([#14930](https://github.com/jestjs/jest/pull/14930))
- `[jest-runtime]` [**BREAKING**] Make it mandatory to pass `globalConfig` to the `Runtime` constructor ([#15044](https://github.com/jestjs/jest/pull/15044))
- `[jest-runtime]` Add `unstable_unmockModule` ([#15080](https://github.com/jestjs/jest/pull/15080))
- `[@jest/schemas]` Upgrade `@sinclair/typebox` to v0.31 ([#14072](https://github.com/jestjs/jest/pull/14072))
- `[@jest/types]` `test.each()`: Accept a readonly (`as const`) table properly ([#14565](https://github.com/jestjs/jest/pull/14565))
- `[@jest/types]` Improve argument type inference passed to `test` and `describe` callback functions from `each` tables ([#14920](https://github.com/jestjs/jest/pull/14920))
Expand Down
48 changes: 48 additions & 0 deletions docs/ECMAScriptModules.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,54 @@ const {execSync} = await import('node:child_process');
// etc.
```

## Module unmocking in ESM

```js title="esm-module.mjs"
export default () => {
return 'default';
};

export const namedFn = () => {
return 'namedFn';
};
```

```js title="esm-module.test.mjs"
import {jest, test} from '@jest/globals';

test('test esm-module', async () => {
jest.unstable_mockModule('./esm-module.js', () => ({
default: () => 'default implementation',
namedFn: () => 'namedFn implementation',
}));

const mockModule = await import('./esm-module.js');

console.log(mockModule.default()); // 'default implementation'
console.log(mockModule.namedFn()); // 'namedFn implementation'

jest.unstable_unmockModule('./esm-module.js');

const originalModule = await import('./esm-module.js');

console.log(originalModule.default()); // 'default'
console.log(originalModule.namedFn()); // 'namedFn'

/* !!! WARNING !!! Don`t override */
jest.unstable_mockModule('./esm-module.js', () => ({
default: () => 'default override implementation',
namedFn: () => 'namedFn override implementation',
}));

const mockModuleOverride = await import('./esm-module.js');

console.log(mockModuleOverride.default()); // 'default implementation'
console.log(mockModuleOverride.namedFn()); // 'namedFn implementation'
});
```

## Mocking CJS modules

For mocking CJS modules, you should continue to use `jest.mock`. See the example below:

```js title="main.cjs"
Expand Down
10 changes: 9 additions & 1 deletion e2e/__tests__/__snapshots__/nativeEsm.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,20 @@ Ran all test suites matching native-esm-wasm.test.js."
exports[`runs test with native ESM 1`] = `
"Test Suites: 1 passed, 1 total
Tests: 33 passed, 33 total
Tests: 31 passed, 31 total
Snapshots: 0 total
Time: <<REPLACED>>
Ran all test suites matching native-esm.test.js."
`;
exports[`runs test with native mock ESM 1`] = `
"Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: <<REPLACED>>
Ran all test suites matching native-esm-mocks.test.js."
`;
exports[`support re-exports from CJS of core module 1`] = `
"Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Expand Down
16 changes: 16 additions & 0 deletions e2e/__tests__/nativeEsm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,22 @@ test('runs test with native ESM', () => {
expect(exitCode).toBe(0);
});

test('runs test with native mock ESM', () => {
const {exitCode, stderr, stdout} = runJest(
DIR,
['native-esm-mocks.test.js'],
{
nodeOptions: '--experimental-vm-modules --no-warnings',
},
);

const {summary} = extractSummary(stderr);

expect(summary).toMatchSnapshot();
expect(stdout).toBe('');
expect(exitCode).toBe(0);
});

test('supports top-level await', () => {
const {exitCode, stderr, stdout} = runJest(DIR, ['native-esm.tla.test.js'], {
nodeOptions: '--experimental-vm-modules --no-warnings',
Expand Down
45 changes: 45 additions & 0 deletions e2e/native-esm/__tests__/native-esm-mocks.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {jest as jestObject} from '@jest/globals';

afterEach(() => {
jestObject.resetModules();
});

test('can mock module', async () => {
jestObject.unstable_mockModule('../mockedModule.mjs', () => ({foo: 'bar'}), {
virtual: true,
});

const importedMock = await import('../mockedModule.mjs');

expect(Object.keys(importedMock)).toEqual(['foo']);
expect(importedMock.foo).toBe('bar');
});

test('can mock transitive module', async () => {
jestObject.unstable_mockModule('../index.js', () => ({foo: 'bar'}));

const importedMock = await import('../reexport.js');

expect(Object.keys(importedMock)).toEqual(['foo']);
expect(importedMock.foo).toBe('bar');
});

test('can unmock module', async () => {
jestObject.unstable_mockModule('../index.js', () => ({
double: () => 1000,
}));

const importedMock = await import('../index.js');
expect(importedMock.double()).toBe(1000);

jestObject.unstable_unmockModule('../index.js');

const importedMockAfterUnmock = await import('../index.js');
expect(importedMockAfterUnmock.double(2)).toBe(4);
});
20 changes: 0 additions & 20 deletions e2e/native-esm/__tests__/native-esm.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,26 +224,6 @@ test('require of ESM should throw correct error', () => {
);
});

test('can mock module', async () => {
jestObject.unstable_mockModule('../mockedModule.mjs', () => ({foo: 'bar'}), {
virtual: true,
});

const importedMock = await import('../mockedModule.mjs');

expect(Object.keys(importedMock)).toEqual(['foo']);
expect(importedMock.foo).toBe('bar');
});

test('can mock transitive module', async () => {
jestObject.unstable_mockModule('../index.js', () => ({foo: 'bar'}));

const importedMock = await import('../reexport.js');

expect(Object.keys(importedMock)).toEqual(['foo']);
expect(importedMock.foo).toBe('bar');
});

test('supports imports using "node:" prefix', () => {
expect(dns).toBe(prefixDns);
});
Expand Down
6 changes: 6 additions & 0 deletions packages/jest-environment/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,12 @@ export interface Jest {
* real module).
*/
unmock(moduleName: string): Jest;
/**
* Indicates that the module system should never return a mocked version of
* the specified module when it is being imported (e.g. that it should always
* return the real module).
*/
unstable_unmockModule(moduleName: string): Jest;
/**
* Instructs Jest to use fake versions of the global date, performance,
* time and timer APIs. Fake timers implementation is backed by
Expand Down
11 changes: 11 additions & 0 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2159,6 +2159,16 @@ export default class Runtime {
this._explicitShouldMock.set(moduleID, false);
return jestObject;
};
const unmockModule = (moduleName: string) => {
const moduleID = this._resolver.getModuleID(
this._virtualModuleMocks,
from,
moduleName,
{conditions: this.esmConditions},
);
this._explicitShouldMockModule.set(moduleID, false);
return jestObject;
};
const deepUnmock = (moduleName: string) => {
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
Expand Down Expand Up @@ -2414,6 +2424,7 @@ export default class Runtime {
spyOn,
unmock,
unstable_mockModule: mockModule,
unstable_unmockModule: unmockModule,
useFakeTimers,
useRealTimers,
};
Expand Down
4 changes: 4 additions & 0 deletions packages/jest-types/__typetests__/jest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ expect(
.setMock('moduleName', {a: 'b'})
.setTimeout(6000)
.unmock('moduleName')
.unstable_unmockModule('moduleName')
.useFakeTimers()
.useFakeTimers({legacyFakeTimers: true})
.useRealTimers(),
Expand Down Expand Up @@ -183,6 +184,9 @@ expect(jest.setMock('moduleName')).type.toRaiseError();
expect(jest.unmock('moduleName')).type.toBe<typeof jest>();
expect(jest.unmock()).type.toRaiseError();

expect(jest.unstable_unmockModule('moduleName')).type.toBe<typeof jest>();
expect(jest.unstable_unmockModule()).type.toRaiseError();

// Mock Functions

expect(jest.clearAllMocks()).type.toBe<typeof jest>();
Expand Down

0 comments on commit 9c9ce8a

Please sign in to comment.