Skip to content

Instantly share code, notes, and snippets.

@danilobatistaqueiroz
Last active April 18, 2026 13:14
Show Gist options
  • Select an option

  • Save danilobatistaqueiroz/da40b12c05e77d8d58d140977206fe4c to your computer and use it in GitHub Desktop.

Select an option

Save danilobatistaqueiroz/da40b12c05e77d8d58d140977206fe4c to your computer and use it in GitHub Desktop.
React and Jest

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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment