feat: add support unstable_unmockModule (#15080)

This commit is contained in:
Aleksei Bondarenko 2024-06-30 15:48:55 +04:00 committed by GitHub
parent d65d4cc662
commit 9c9ce8ad80
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 140 additions and 21 deletions

View File

@ -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))

View File

@ -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"

View File

@ -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

View File

@ -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',

View File

@ -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);
});

View File

@ -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);
});

View File

@ -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

View File

@ -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,
@ -2414,6 +2424,7 @@ export default class Runtime {
spyOn,
unmock,
unstable_mockModule: mockModule,
unstable_unmockModule: unmockModule,
useFakeTimers,
useRealTimers,
};

View File

@ -51,6 +51,7 @@ expect(
.setMock('moduleName', {a: 'b'})
.setTimeout(6000)
.unmock('moduleName')
.unstable_unmockModule('moduleName')
.useFakeTimers()
.useFakeTimers({legacyFakeTimers: true})
.useRealTimers(),
@ -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>();