How to use Cypress code coverage with Next.js using Babel only for tests and Turbopack for development? #32685
Replies: 1 comment
-
|
This is a tricky setup since Turbopack and Babel are fundamentally different transpilers, and Next.js disables Babel entirely when Turbopack is active. The key insight: you need to run Next.js without Turbopack during Cypress tests so Babel instrumentation can kick in. Here's how to set it up cleanly: 1. Separate dev vs. test scripts{
"scripts": {
"dev": "next dev --turbopack",
"dev:test": "next dev",
"cy:open": "cypress open",
"cy:run": "cypress run",
"test:e2e": "start-server-and-test dev:test http://localhost:3000 cy:run"
}
}The 2. Conditional Babel configCreate a module.exports = function (api) {
// Only instrument when running in Cypress test mode
const isTest = process.env.CYPRESS_COVERAGE === "true" || process.env.NODE_ENV === "test"
const plugins = []
if (isTest) {
plugins.push("istanbul")
}
return {
presets: ["next/babel"],
plugins,
}
}Then set the env variable in your test script: {
"test:e2e": "CYPRESS_COVERAGE=true start-server-and-test dev:test http://localhost:3000 cy:run"
}3. Install dependenciesnpm install --save-dev babel-plugin-istanbul @cypress/code-coverage start-server-and-test4. Cypress support fileIn import "@cypress/code-coverage/support"5. Coverage API routeFor the Page Router, create export default function handler(req, res) {
res.status(200).json({
coverage: global.__coverage__ || null,
})
}Why this works
The trade-off is that your test server will be slower than Turbopack, but that's unavoidable — code coverage instrumentation requires a Babel transform, and Turbopack doesn't support Babel plugins. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
I’m trying to configure Cypress code coverage in a Next.js project that uses Turbopack for development, but I want to use Babel only during testing — without affecting the dev or production builds.
I’ve been using this example as a reference:
👉 bahmutov/next-and-cypress-example
cypress.config.ts
What I need help with
Additional Info
Beta Was this translation helpful? Give feedback.
All reactions