-
-
Notifications
You must be signed in to change notification settings - Fork 6.6k
Closed as not planned
Closed as not planned
Copy link
Description
Version
29.7.0
Steps to reproduce
Jest Hoisting Bug Proof of Concept for .cjs files
Setup Instructions
- Clone the repository:
git clone git@github.com:klocke-io/jestHoistingTest.git cd jestHoistingTest - Install dependencies:
npm install
- Run specific test files:
For the.jstest: (Works as expected ✅)For thenpx jest __tests__/index.spec.js
.cjstest: (Dose not work as expected ❌)For the manually hoistednpx jest __tests__/index.spec.cjs
.cjstest (Works as expected ✅):npx jest __tests__/index.manually-hoisted.cjs
Expected behavior
- tests/index.spec.cjs:
jest.mockshould 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.mockdoes not work in.cjsfiles, but works in.jsfiles. Manual hoisting (placingjest.mockbeforerequire) is required for.cjsfiles.
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