Windsurf testing

Jest Mocking Not Working with ESM in Windsurf Project

Jest mocking doesn't work in your Windsurf-generated project that uses ES modules (ESM). jest.mock() calls are silently ignored, mocked modules still return real implementations, or you get errors about import statements not being mockable. Tests that should use mocked dependencies are hitting real APIs or databases.

This is one of the most common testing frustrations in modern JavaScript projects. Jest was designed for CommonJS (require), and its mocking system doesn't work the same way with ESM imports. Cascade generates test files with jest.mock() patterns that only work in CommonJS, leading to tests that appear to set up mocks correctly but actually use the real modules.

You might notice this when tests make real HTTP requests, modify your actual database, or fail with authentication errors — all signs that mocking isn't working and real dependencies are being used.

Error Messages You Might See

jest.mock() is not allowed in ESM The module factory of jest.mock() is not allowed to reference any out-of-scope variables SyntaxError: Cannot use import statement outside a module Mock not working: received real implementation instead of mock TypeError: jest.unstable_mockModule is not a function
jest.mock() is not allowed in ESMThe module factory of jest.mock() is not allowed to reference any out-of-scope variablesSyntaxError: Cannot use import statement outside a moduleMock not working: received real implementation instead of mockTypeError: jest.unstable_mockModule is not a function

Common Causes

  • jest.mock() hoisting doesn't work with ESM — In CommonJS, Jest hoists jest.mock() calls to the top of the file. With ESM, import statements are evaluated before any code runs, so mocks aren't in place when imports execute
  • Missing babel/ts-jest transformation — Without proper transformation, import statements aren't converted to requires, and Jest's mock system can't intercept them
  • Using import instead of require in mock setup — Mocked modules imported with static import get the real module, not the mock
  • jest.config using wrong transform — The Jest configuration doesn't have the correct transform for .ts or .tsx files with ESM syntax
  • Mock factory function returning wrong shape — The mock factory doesn't match the module's export shape (named exports vs default export)

How to Fix It

  1. Use jest.unstable_mockModule for ESM — Replace jest.mock() with jest.unstable_mockModule() and use dynamic import() after setting up mocks
  2. Configure ts-jest or babel-jest properly — Ensure your Jest config transforms ESM to CJS: transform: { '^.+\\.tsx?$': 'ts-jest' } with useESM: true in ts-jest config
  3. Use dependency injection instead — Refactor code to accept dependencies as parameters rather than importing them directly. This makes testing trivial regardless of module system
  4. Match mock shape to real module — For named exports, return an object with all exported names. For default exports, use { __esModule: true, default: mockFn }
  5. Consider Vitest as an alternative — Vitest has native ESM support and a Jest-compatible API. Migration is often straightforward and fixes ESM mocking issues
  6. Use manual mocks in __mocks__ directory — Create a __mocks__/module-name.ts file that Jest automatically uses. This approach works with both CJS and ESM

Real developers can help you.

PawelPloszaj PawelPloszaj I'm fronted developer with 10+ years of experience with big projects. I have small backend background too Jared Hasson Jared Hasson Full time lead founding dev at a cyber security saas startup, with 10 yoe and a bachelor's in CS. Building & debugging software products is what I've spent my time on for forever Jaime Orts-Caroff Jaime Orts-Caroff I'm a Senior Android developer, open to work in various fields Costea Adrian Costea Adrian Embedded Engineer specilizing in perception systems. Latest project was a adas camera calibration system. Sage Fulcher Sage Fulcher Hey I'm Sage! Im a Boston area software engineer who grew up in South Florida. Ive worked at a ton of cool places like a telehealth kidney care startup that took part in a billion dollar merger (Cricket health/Interwell health), a boutique design agency where I got to work on a ton of exciting startups including a photography education app, a collegiate Esports league and more (Philosophie), a data analytics as a service startup in Cambridge (MA) as well as at Phillips and MIT Lincoln Lab where I designed and developed novel network security visualizations and analytics. I've been writing code and furiously devoted to using computers to make people’s lives easier for about 17 years. My degree is in making computers make pretty lights and sounds. Outside of work I love hip hop, the Celtics, professional wrestling, magic the gathering, photography, drumming, and guitars (both making and playing them) Simon A. Simon A. I'm a backend developer building APIs, emulators, and interactive game systems. Professionally, I've developed Java/Spring reporting solutions, managed relational and NoSQL databases, and implemented CI/CD workflows. Stanislav Prigodich Stanislav Prigodich 15+ years building iOS and web apps at startups and enterprise companies. I want to use that experience to help builders ship real products - when something breaks, I'm here to fix it. MFox MFox Full-stack professional senior engineer (15+years). Extensive experience in software development, qa, and IP networking. Alvin Voo Alvin Voo I’ve watched the tech landscape evolve over the last decade—from the structured days of Java Server Pages to the current "wild west" of Agentic-driven development. While AI can "vibe" a frontend into existence, I specialize in the architecture that keeps it from collapsing. My expertise lies in the critical backend infrastructure: the parts that must be fast, secure, and scalable. I thrive on high-pressure environments, such as when I had only three weeks to architect and launch an Ethereum redemption system with minimal prior crypto knowledge, turning it into a major revenue stream. What I bring to your project: Forensic Debugging: I don't just "patch" bugs; I use tools like Datadog and Explain Analyzers to map out bottlenecks and resolve root causes—like significantly reducing memory usage by optimizing complex DB joins. Full-Stack Context: Deep experience in Node.js and React, ensuring backends play perfectly with mobile and web teams. Sanity in the Age of AI: I bridge the gap between "best practices" and modern speed, ensuring your project isn't just built fast, but built to last. Antriksh Narang Antriksh Narang 5 years+ Experienced Dev (Specially in Web Development), can help in python, javascript, react, next.js and full stack web dev technologies.

You don't need to be technical. Just describe what's wrong and a verified developer will handle the rest.

Get Help

Frequently Asked Questions

Why doesn't jest.mock() work with ES modules?

jest.mock() relies on hoisting the mock setup before require() calls. With ESM, import statements are resolved at parse time before any code runs, so jest.mock() hasn't executed yet when imports are resolved. Use jest.unstable_mockModule() with dynamic import() instead.

Should I switch from Jest to Vitest?

If you're fighting ESM mocking issues, Vitest is worth considering. It has native ESM support, a nearly identical API to Jest, and handles module mocking natively. Migration is usually just changing imports and config, not rewriting tests.

Related Windsurf Issues

Can't fix it yourself?
Real developers can help.

You don't need to be technical. Just describe what's wrong and a verified developer will handle the rest.

Get Help