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.

Yovel Cohen Yovel Cohen I got a lot of experience in building Long-horizon AI Agents in production, Backend apps that scale to millions of users and frontend knowledge as well. PawelPloszaj PawelPloszaj I'm fronted developer with 10+ years of experience with big projects. I have small backend background too Mehdi Ben Haddou Mehdi Ben Haddou - Founder of Chessigma (1M+ users) & many small projects - ex Founding Engineer @Uplane (YC F25) - ex Software Engineer @Amazon and @Booking.com Dor Yaloz Dor Yaloz SW engineer with 6+ years of experience, I worked with React/Node/Python did projects with React+Capacitor.js for ios Supabase expert Krishna Sai Kuncha Krishna Sai Kuncha Experienced Professional Full stack Developer with 8+ years of experience across react, python, js, ts, golang and react-native. Developed inhouse websearch tooling for AI before websearch was solved : ) Luca Liberati Luca Liberati I work on monoliths and microservices, backends and frontends, manage K8s clusters and love to design apps architecture zipking zipking I am a technologist and product builder dedicated to creating high-impact solutions at the intersection of AI and specialized markets. Currently, I am focused on PropScan (EstateGuard), an AI-driven SaaS platform tailored for the Japanese real estate industry, and exploring the potential of Archify. As an INFJ-T, I approach development with a "systems-thinking" mindset—balancing technical precision with a deep understanding of user needs. I particularly enjoy the challenge of architecting Vertical AI SaaS and optimizing Small Language Models (SLMs) to solve specific, real-world business problems. Whether I'm in a CTO-level leadership role or hands-on with the code, I thrive on building tools that turn complex data into actionable value. Anthony Akpan Anthony Akpan Developer with 8 years of experience building softwares fro startups 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) Omar Faruk Omar Faruk As a Product Engineer at Klasio, I contributed to end-to-end product development, focusing on scalability, performance, and user experience. My work spanned building and refining core features, developing dynamic website templates, integrating secure and reliable payment gateways, and optimizing the overall system architecture. I played a key role in creating a scalable and maintainable platform to support educators and learners globally. I'm enthusiastic about embracing new challenges and making meaningful contributions.

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