To run Jest with React you'll need:
To add to root folder:
jest.config.js
jest.setup.js
Install the packages:
- jest
- jest-environment-jsdom
- @types/jest
- @testing-library/react
- @testing-library/jest-dom
Content of jest.setup.js
// Learn more: https://github.com/testing-library/jest-dom
import "@testing-library/jest-dom";Content of 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: ["<rootDir>/jest.setup.js"],
testEnvironment: "jsdom",
/** if you use only ESM packages, Jest needs to transpile before each execution, currency-codes-ts and lodash-es are examples */
/** You can configure next.config.ts to build and transpile your only ESM packages to CJS its preferable if you have many packages */
transformIgnorePatterns: [
'node_modules/(?!(currency-codes-ts|lodash-es)/)'
]
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);If that config above doesn't work, the Jest version maybe require an async export:
Content of jest.config.js
const nextJest = require("next/jest");
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
const createJestConfig = nextJest({
dir: "./",
});
// Add any custom config to be passed to Jest
const config = {
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
testEnvironment: "jsdom",
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
async function jestConfig() {
const nextJestConfig = await createJestConfig(config)();
nextJestConfig.transformIgnorePatterns[0] = '/node_modules/(?!())/';
return nextJestConfig;
}
module.exports = jestConfig;