Jest Config

Jest config for Hybrid Projects (like Next.js)

Avatar

Manpreet Minhas

2 min read · Oct 24, 2024 · 1 likes

In projects like Next.js where you have both frontend and backend code, you may use testEnvironment: 'jest-environment-jsdom' for testing client-side rendering, components, and UI logic. Use testEnvironment: 'node' for testing server-side logic (like API routes and server-side rendering).

  • Frontend tests (e.g., testing React components) should use jest-environment-jsdom.
  • Backend tests (e.g., testing API routes, server-side code) should use jest-environment-node or node.
You can specify the environment directly in each test file using a comment at the top of the file. This allows you to choose the right environment based on what you are testing.

For backend tests API routes, server-side logic) use


/**
 * @jest-environment node
 */

For a frontend test (React components, UI logic) use


/**
 * @jest-environment jsdom
 */

If you want to automatically assign environments based on the location of your test files, you can configure Jest to use different environments depending on the folder. In your jest.config.js, you can specify different configurations for different file patterns. Here's how you can do it:


const nextJest = require('next/jest');

const createJestConfig = nextJest({ dir: './' });

const customJestConfig = {
  setupFilesAfterEnv: ['/jest.setup.js'],
  moduleNameMapper: {
    '^@/(.*)$': '/$1',
  },
  // Default to jsdom for frontend tests
  testEnvironment: 'jest-environment-jsdom',
  testMatch: ['/**/*.test.(js|jsx|ts|tsx)'], // Add your test file patterns here
  // Add custom environments for different folders
  projects: [
    {
      displayName: 'frontend',
      testMatch: ['/tests/frontend/**/*.test.(js|jsx|ts|tsx)'],
      testEnvironment: 'jest-environment-jsdom',
    },
    {
      displayName: 'backend',
      testMatch: ['/tests/backend/**/*.test.(js|jsx|ts|tsx)'],
      testEnvironment: 'node',
    },
  ],
};

module.exports = createJestConfig(customJestConfig);