Skip to content

[Bug]: Jest.mock is not hoisted for .cjs files in a commonjs project #15657

@klocke-io

Description

@klocke-io

Version

29.7.0

Steps to reproduce

Jest Hoisting Bug Proof of Concept for .cjs files

Setup Instructions

Example Repo

  1. Clone the repository:
    git clone git@github.com:klocke-io/jestHoistingTest.git
    cd jestHoistingTest
  2. Install dependencies:
    npm install
  3. Run specific test files:
    For the .js test: (Works as expected ✅)
    npx jest __tests__/index.spec.js
    For the .cjs test: (Dose not work as expected ❌)
    npx jest __tests__/index.spec.cjs
    For the manually hoisted .cjs test (Works as expected ✅):
    npx jest __tests__/index.manually-hoisted.cjs

Expected behavior

  • tests/index.spec.cjs: jest.mock should be hoisted, to the top of the file, independent of the file extension (.js | .cjs)
    // __tests__/index.spec.cjs
    const { businessMessage } = require('../lib');
    jest.mock('../lib', () => ({
      businessMessage: jest.fn(() => 'mocked!'),
    }));
    
    test('should use the mocked implementation', () => {
      expect(businessMessage()).toBe('mocked!');
    });
    // This test will fail because jest.mock is not hoisted in .cjs files

Actual behavior

jest.mock should be hoisted, to the top of the file, independent of the file extension (.js | .cjs)

Additional context

Key Point

  • Jest's automatic hoisting of jest.mock does not work in .cjs files, but works in .js files. Manual hoisting (placing jest.mock before require) is required for .cjs files.

I tried to place everything usefull in here, If I missed anything, or you need more information. Please let me know, I will try to get back asap

Environment

## Test Environment 

- **Node.js version:** v23.10.0
- **npm version:** 10.9.2
- **npx version:** 10.9.2
- **Jest version:** 29.7.0
- **OS:** macOS 15.5 (Darwin Kernel Version 24.5.0, arm64)

### Command: 

node --version
npm --version
npx --version
npx jest --version
uname -a
sw_vers


### Output:

v23.10.0
10.9.2
10.9.2
29.7.0
Darwin LQ9357DK4K 24.5.0 Darwin Kernel Version 24.5.0: Tue Apr 22 19:53:27 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T6041 arm64
ProductName:            macOS
ProductVersion:         15.5
BuildVersion:           24F74

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