Skip to content

[Bug]: unstable_mockModule doesn't mock anymore  #15690

@Luligu

Description

@Luligu

Version

30.0.2

Steps to reproduce

// src\esm-fs-unstable-mock.ts

// ESM unstable mock of 'node:fs'

/* eslint-disable no-console */

console.log('Loaded esm-fs-unstable-mock.ts.', process.cwd());

import { existsSync } from 'node:fs';

/**
 * Function to check if a file named 'not_a_file' exists.
 *
 * @returns {boolean} - Returns true if 'not_a_file' exists, false otherwise.
 */
export function not_a_file(): boolean {
  const not_a_file_exists = existsSync('not_a_file');
  console.log(`not_a_file exist ${not_a_file_exists}`);
  return not_a_file_exists;
}

// src\esm-fs-unstable-mock.test.ts

// ESM unstable mock of 'node:fs'

jest.unstable_mockModule('node:fs', () => {
  const originalModule = jest.requireActual<typeof import('node:fs')>('node:fs');
  return {
    ...originalModule,

    existsSync: jest.fn<typeof existsSync>((path: PathLike) => {
      return originalModule.existsSync(path);
    }),
  };
});
const { existsSync, promises } = await import('node:fs');
import type { PathLike } from 'node:fs';

import { jest } from '@jest/globals';

describe('ESM module node:fs unstable mock test', () => {
  it('should check the ESM mock module', async () => {
    const not_a_file = (await import('../src/esm-fs-unstable-mock.ts')).not_a_file;
    expect(not_a_file).toBeDefined();

    // Before mocking, check the original behavior
    expect(not_a_file()).toBe(false);

    // Mock the existsSync function to always return true
    (existsSync as jest.Mocked<typeof existsSync>).mockImplementation((path: PathLike) => {
      return true;
    });
    expect(not_a_file()).toBe(true);
  });
});

Expected behavior

Hi,
I have thousands of test using often unstable_mockModule in all packages.

Before version 30.0.0 I never had any issues.

Now with 30.0.2 the unstable_mockModule doesn't mock anymore when the module under test call the mocked method.

Actual behavior

With 30.0.2 the unstable_mockModule doesn't mock anymore when the module under test call the mocked method.

Am I missing something ?

Additional context

Is I downgrade to 29.7.0 all is working.

Environment

System:
    OS: Linux 6.6 Debian GNU/Linux 12 (bookworm) 12 (bookworm)
    CPU: (12) arm64 unknown
  Binaries:
    Node: 22.16.0 - /usr/local/bin/node
    Yarn: 1.22.22 - /usr/local/bin/yarn
    npm: 11.4.2 - /usr/local/share/npm-global/bin/npm
    pnpm: 10.12.1 - /usr/local/share/npm-global/bin/pnpm
  npmPackages:
    jest: ^30.0.2 => 30.0.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions