We would like to add code coverage to a setup where we use cypress and nextjs. In our cypress config we build nextJs using next() to mock the backend requests inside nextjs.
The cypress.config.ts looks like this:
async setupNodeEvents(on, config) {
...
const app = next({ dev, hostname, port }) // Build application in tests env
const handle = app.getRequestHandler()
await app.prepare().then(() => {
createServer(async (req, res) => { // Create server and start application
...
const parsedUrl = parse(req.url!, true)
await handle(req, res, parsedUrl)
...
}).listen(port, () => {
console.log(`> Ready on https://${hostname}:${port}`)
})
})
With this setup we can mock tests with nock while testing e2e. Quite similar to this setup: https://glebbahmutov.com/blog/mock-network-from-server/
The problem we are facing now is how to add Code Coverage to this application? We weren't able to instrument the code. Does anybody did this or can link a repo where this is done? Any tipps would help.
So the answer would be it depends. I suggest looking into nextjs swc discussion. Search for coverage and you will find multiple some are hacky ways to do it. This process has 2 steps:
Create Coverage. I suggest following cypress docs. Ignore babel instructions. setup @cypress/code-coverage. While you test run it should say something about coverage. Image in the docs.
Instrument you code. Instead of babel I suggest using swc-plugin-coverage-instrument. So the steps would be:
It even works with app-router with some adjustments here
Here's examples
Using Babel. You could probably also simply create .babelrc file, and nextjs will automatically fall back to using babel for transforming individual files. and simply follow cypress code coverage instructions. However nextjs is moving away from babel so this would be a step backwards.