proposal: add `MockModuleOptions.preserveOthers`
@JakobJingleheimer arbeitet bereits daran.
Seit 24.5.2025.
Bewertung
Dieses Issue wurde noch nicht bewertet.
Beschreibung
This would simplify mocking only a subset of a module's exports. A common use-case for this is a method that will do something undesirable in a test environment, like start a server.
Currently, it's possible with some non-obvious gymnastics:
describe('Example', () => {
let example;
before(async () => {
example = await import('./example.mjs');
const theMock = mock.module('./example.mjs', {
namedExports: {
...example,
theOneThingToMock: mock.fn(),
},
});
// Must do this again!
example = await import('./example.mjs');
});
});
Instead, with preserveOthers, it's more straightforward:
describe('Example', () => {
let example;
before(async () => {
const theMock = mock.module('./example.mjs', {
namedExports: {
theOneThingToMock: mock.fn(),
},
preserveOthers: true,
});
example = await import('./example.mjs');
});
});
There is some hidden complexity in the implementation though: When a module is loaded, it’s immediately added to the module cache (which is controlled by V8—node can’t manipulate it).
So we’ll need to do some trickery like initially load the module with a query param appended to the specifier (which may already have a query param of its own 🤪), grab the exports and cache them for as long as the module is in scope: A module can be mocked multiple times, potentially with different replacements. We’ll need to diff replacements and original.
This would also facilitate supporting a feature like Jest's requireActual: theMock.getOriginal.
- Vorherrschende Sprache
- Keine Sprachdaten
- Sterne
- 3
- Forks
- 4
- PR-Merge-Kennzahlen
- Keine gemergten PRs in 30 T.
Entwicklungsumgebung
- Kein Dockerfile und keine Docker-Compose-Datei
- Keine Pull-Request-Vorlage
- Beitragsleitfaden lesen
Erste Schritte
- Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
- Forken Sie das Repository und arbeiten Sie in einem Branch.
- Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.
Mehr aus nodejs/test-runner
-
Schwierigkeit 1/5 Unter einer Stunde Anfängerfreundlichkeit 1/100
nodejs/test-runner#46 ·
-
Schwierigkeit 1/5 Unter einer Stunde Anfängerfreundlichkeit 5/100
nodejs/test-runner#45 ·
-
Schwierigkeit 1/5 Unter einer Stunde Anfängerfreundlichkeit 10/100
nodejs/test-runner#44 ·
-
Schwierigkeit 1/5 Unter einer Stunde Anfängerfreundlichkeit 15/100
nodejs/test-runner#43 ·
-
Schwierigkeit 1/5 Unter einer Stunde Anfängerfreundlichkeit 15/100
nodejs/test-runner#42 ·