Skip to main content
BLOG.siposdani87

Setup Cypress coverage on TypeScript Next.js 12

Configure Cypress end-to-end testing in a TypeScript Next.js 12 project

By Dániel Sipos
· · 1 min read

Note: This article targets Next.js 12 and an older version of Cypress that uses the cypress/integration directory. Modern Cypress (v10+) uses cypress/e2e instead. Adapt the directory paths accordingly for newer versions.

To set up Cypress for a Next.js project, you can follow these steps:

Install Cypress using npm:

npm install --save-dev cypress

Initialize Cypress by running the following command:

npx cypress init

Modify the package.json file to add a script for running Cypress tests:

"scripts": {
  "cypress:open": "cypress open",
  "cypress:run": "cypress run"
},

In your Next.js server.js file, add the following code to start the server in development mode when running Cypress tests:

if (process.env.CYPRESS_ENV === 'development') {
	require('next/dist/server/next')().start(3000);
}

Create a test file in the cypress/integration directory. For example, you could create a file called test.js with the following content:

describe('My test', () => {
	it('visits the homepage', () => {
		cy.visit('http://localhost:3000');
	});
});

Run the Cypress test runner using the following command:

npm run cypress:open

This will open the Cypress test runner, where you can view and run your tests.

Conclusion

This setup provides a basic Cypress integration for end-to-end testing in a Next.js 12 TypeScript project. For code coverage reporting, consider adding the @cypress/code-coverage plugin with Istanbul instrumentation.

Share with your friends

Related posts