proposal: add `MockModuleOptions.preserveOthers`

Abierto
#32 1 comentario 5 reacciones 1 asignado Ver en GitHub

@JakobJingleheimer ya está trabajando en esto.

Desde el 24/5/2025.

Evaluación

Este issue todavía no se ha evaluado.

Descripción

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.

Lenguaje dominante
Sin datos de lenguaje
Estrellas
3
Forks
4
Métricas de merge de PR
Sin PR fusionados en 30 d

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de nodejs/test-runner

Todos los issues de nodejs/test-runner

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.