Correctly configure Cypress and Jest on a Typescript NextJS project
March 22, 2023
Outline
Install and configure Cypress
Install and configure Jest
Install and configure Cypress
Install Cypress dependencies
npm install cypress --save-dev
To automatically let Cypress add the needed files run
npx cypress open
Install testing library Cypress to easily query elements
npm install --save-dev @testing-library/cypress
Add this line to your project cypress/support/commands.ts file
import '@testing-library/cypress/add-commands'
In the cypress folder add a new tsconfig.json
file:
{
"extends": "../tsconfig.json",
"include": ["./**/*.cy.ts"],
"exclude": [],
"compilerOptions": {
"types": ["cypress", "@testing-library/cypress"],
"lib": ["es2015", "dom"],
"isolatedModules": false,
"allowJs": true,
"noEmit": true
}
}
If you don't add this tsconfig.json file under the cypress folder you will get the following typescript error when adding jest test files
Property 'toBeInTheDocument' does not exist on type 'Assertion'.ts(2339)
Add a new spec file to test the home page
Under the e2e folder add a file called home.cy.ts
describe("Home page", () => {
it("passes", () => {
cy.visit("http://localhost:3000");
cy.findByText("Get started by editing").should("exist");
});
});
If you run the test everything should run correctly
Install and configure Jest
Add the following dependencies
npm install --save-dev jest @testing-library/jest-dom @testing-library/react @types/testing-library__jest-dom jest-environment-jsdom
Add file jest.config.js
const nextJest = require("next/jest");
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: "./",
});
// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ["./jest.setup.js"],
moduleNameMapper: {
// Handle module aliases (this will be automatically configured for you soon)
"^@/components/(.*)$": "<rootDir>/components/$1",
"^@/pages/(.*)$": "<rootDir>/pages/$1",
},
testEnvironment: "jest-environment-jsdom",
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
Add file jest.setup.js
Add the following line to that file
import '@testing-library/jest-dom/extend-expect';
Add the following to the “exclude” section of the root tsconfig.json file
"exclude": ["node_modules", "./cypress.config.ts", "cypress"]
Add a __tests__
folder and add a new jest test home.test.tsx
import Home from "@/pages/index";
import { render, screen } from "@testing-library/react";
describe("PasswordShowTextField", () => {
it("renders a heading", async () => {
render(<Home />);
expect(screen.getByText("Get started by editing")).toBeInTheDocument();
});
});
Complete source code:
https://codesandbox.io/p/github/xap5xap/cypress-jest/main