proposal: add `MockModuleOptions.preserveOthers`

未关闭
#32 1 条评论 5 个 reaction 已指派 1 人 在 GitHub 查看

@JakobJingleheimer 已经在做这个了。

开始于 2025年5月24日。

评估

这个 Issue 还没有评估数据。

描述

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.

主要语言
没有语言数据
星标
3
派生
4
PR 合并指标
30 天内没有已合并 PR

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

nodejs/test-runner 的其他 Issue

查看 nodejs/test-runner 的全部 Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。