new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js · Guides · all subjects

testing/jest

24 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Jest and React Testing Library use cases

Jest and React Testing Library are frequently used together for Unit Testing and Snapshot Testing in Next.js projects.

Async Server Components Jest limitation

Jest currently does not support async Server Components. Unit tests can still run for synchronous Server and Client Components, but E2E tests are recommended for async components.

Create Next.js app with Jest example

Use create-next-app with the with-jest example to quickly set up Jest with Next.js. Run: pnpm create next-app --example with-jest with-jest-app (or npm/yarn/bun equivalent).

Jest built-in configuration

Next.js has had built-in configuration for Jest since version 12, allowing automatic setup without manual configuration.

Jest manual setup packages

To manually set up Jest with Next.js, install these packages as dev dependencies: jest, jest-environment-jsdom, @testing-library/react, @testing-library/dom, @testing-library/jest-dom, ts-node, @types/jest.

next/jest configuration

Update the Jest config file to use next/jest transformer, which contains all necessary configuration options for Jest to work with Next.js. The createJestConfig function requires a dir option with the path to the Next.js app (e.g., './') to load next.config.js and .env files.

Jest config example JavaScript

Example jest.config.js using next/jest: Require next/jest. Create createJestConfig via nextJest({ dir: './' }). Define config object with coverageProvider: 'v8' and testEnvironment: 'jsdom'. Export via module.exports = createJestConfig(config).

next/jest automatic configuration

The next/jest transformer automatically configures Jest by: setting up transform using Next.js Compiler, auto-mocking stylesheets (.css, .module.css, and scss variants), image imports and next/font, loading .env files into process.env, ignoring node_modules from test resolving and transforms, ignoring .next from test resolving, and loading next.config.js for SWC transform flags.

Test environment variables

To test environment variables directly, load them manually in a separate setup script or in the jest.config.ts file.

Jest with Babel configuration

If opting out of the Next.js Compiler and using Babel instead, manually configure Jest and install babel-jest and identity-obj-proxy in addition to standard packages. Configure moduleNameMapper, transform with babel-jest using next/babel preset, and transformIgnorePatterns.

Jest Babel config full reference

Full jest.config.js for Babel setup includes: collectCoverage: true, coverageProvider: 'v8', collectCoverageFrom with glob patterns excluding .d.ts, node_modules, out, .next, config files and coverage, moduleNameMapper for CSS (with/without modules), images, module aliases and next/font, testPathIgnorePatterns for node_modules and .next, testEnvironment: 'jsdom', transform using babel-jest with next/babel preset, transformIgnorePatterns for node_modules and CSS modules.

Mock stylesheets for Jest

Create __mocks__/styleMock.js with module.exports = {} to mock stylesheet imports in tests.

Mock file imports for Jest

Create __mocks__/fileMock.js with module.exports = 'test-file-stub' to mock image and file imports in tests.

Mock next/font in Jest

Create __mocks__/nextFontMock.js with a Proxy that returns an object containing className: 'className', variable: 'variable', and style: { fontFamily: 'fontFamily' } to mock next/font imports.

Module path aliases in Jest

If using module path aliases (baseUrl and paths in tsconfig.json or jsconfig.json), configure Jest to resolve imports by matching paths in the moduleNameMapper option of jest.config.js. For example, "@/components/*": "components/*" in tsconfig paths should match "^@/components/(.*)$": "<rootDir>/components/$1" in moduleNameMapper.

Extend Jest with custom matchers

@testing-library/jest-dom includes custom matchers like .toBeInTheDocument(). To enable them for all tests, add setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'] to jest.config.ts, then import '@testing-library/jest-dom' in jest.setup.ts.

Custom matchers for v6 and later

In @testing-library/jest-dom v6.0 and later, import '@testing-library/jest-dom' directly. For versions before v6, import '@testing-library/jest-dom/extend-expect' instead.

Add Jest test script to package.json

Add to package.json scripts: "test": "jest" and optionally "test:watch": "jest --watch" for running tests on file changes.

Jest test file location

Create a __tests__ folder in the project root directory to store test files.

App Router test file example

Example test for App Router Page component: Import @testing-library/jest-dom, render and screen from @testing-library/react, and Page from ../app/page. Use describe and it blocks with render(<Page />) and screen.getByRole to query elements. Use expect(heading).toBeInTheDocument() assertion.

Snapshot testing in Jest

Use snapshot testing to keep track of unexpected component changes. Call render() to get container, then use expect(container).toMatchSnapshot() to create and compare snapshots.

Test files should not be in Pages Router

Do not include test files inside the Pages Router directory because any files inside the Pages Router are considered routes.

Run Jest tests

Execute tests with: pnpm test, npm run test, yarn test, or bun run test.

Jest CLI options

Jest supports various CLI options like --watch for re-running tests when files change. See Jest documentation for complete reference of CLI options.

Give your agent this brain