proposal: add `MockModuleOptions.preserveOthers`

Đang mở
#32 1 bình luận 5 reaction 1 người được giao Xem trên GitHub

@JakobJingleheimer đang làm issue này rồi.

Từ ngày 24/5/2025.

Đánh giá

Issue này chưa được đánh giá.

Mô tả

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.

Ngôn ngữ chính
Không có dữ liệu ngôn ngữ
Star
3
Fork
4
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của nodejs/test-runner

Tất cả issue của nodejs/test-runner

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.