You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中配置Jest同时测试React组件与数据库逻辑的问题

Next.js Jest双环境配置问题:JSX解析失败且仅Node环境生效

问题描述

我正在开发一个Next.js项目,希望配置Jest以同时使用jsdom环境测试React组件,以及node环境测试数据库相关逻辑。单独配置这两类测试时均能正常运行,但使用projects数组配置双环境时,仅node环境生效,还出现了Jest无法解析JSX语法的Unexpected token '<'错误。尝试过调换projects数组中的配置顺序、删除node环境配置,但问题仍未解决。

配置代码

import type { Config } from "jest";
import nextJest from "next/jest.js";

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

const config: Config = {
  projects: [
    {
      displayName: "react",
      preset: "ts-jest",
      testEnvironment: "jsdom",
      moduleNameMapper: {
        "^@/app/(.*)$": "<rootDir>/app/$1",
      },
      setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
      transform: {
        "^.+\.tsx?$": ["ts-jest", {}],
      },
      testMatch: ["<rootDir>/app/__test__/**/*.jsdom.test.ts?(x)"],
    },
    {
      displayName: "database",
      preset: "ts-jest",
      testEnvironment: "node",
      moduleNameMapper: {
        "^@/app/(.*)$": "<rootDir>/app/$1",
      },
      setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
      transform: {
        "^.+\.tsx?$": ["ts-jest", {}],
      },
      testMatch: ["<rootDir>/app/__test__/**/*.node.test.ts?(x)"],
    },
  ],
};

export default createJestConfig(config);

报错信息

Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.
Details:

    /home/user/app-admin-hub/app/__test__/components/Navigation.jsdom.test.tsx:44
            (0, react_1.render)(<Navigation_1.default />);
                                ^

    SyntaxError: Unexpected token '<'

解决方案

问题根源

nextJest生成的配置会全局覆盖你在projects数组中定义的transform规则,导致jsdom环境下的TSX/JSX文件没有被Next.js的转译工具正确处理;同时测试匹配规则的优先级问题,让node环境的配置误接管了React组件测试文件,最终引发JSX解析失败。

修复后的配置

import type { Config } from "jest";
import nextJest from "next/jest.js";

// 为React测试单独创建Next.js适配的配置生成器
const createReactJestConfig = nextJest({ dir: "./" });

// Node环境测试的独立配置(无需Next.js转译)
const nodeTestConfig: Config = {
  displayName: "database",
  preset: "ts-jest",
  testEnvironment: "node",
  moduleNameMapper: {
    "^@/app/(.*)$": "<rootDir>/app/$1",
  },
  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
  testMatch: ["<rootDir>/app/__test__/**/*.node.test.ts?(x)"],
};

// React环境测试的基础配置
const reactTestBaseConfig: Config = {
  displayName: "react",
  testEnvironment: "jsdom",
  moduleNameMapper: {
    "^@/app/(.*)$": "<rootDir>/app/$1",
  },
  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
  testMatch: ["<rootDir>/app/__test__/**/*.jsdom.test.ts?(x)"],
};

// 异步导出配置,确保Next.js的配置生成完成
export default async () => {
  const finalReactConfig = await createReactJestConfig(reactTestBaseConfig)();
  return {
    projects: [finalReactConfig, nodeTestConfig],
  };
};

关键调整说明

  1. 拆分配置生成逻辑:用nextJest单独处理React测试的配置,确保Next.js内置的TSX/JSX转译规则生效,避免全局配置覆盖问题。
  2. Node测试独立配置:数据库测试不需要Next.js的特殊转译,直接使用ts-jest预设即可,减少不必要的干扰。
  3. 异步导出配置:nextJest的配置生成是异步过程,用异步函数确保配置完全初始化后再合并。

验证方法

  • 单独运行React测试:jest --selectProjects react,确认JSX解析正常
  • 单独运行数据库测试:jest --selectProjects database,验证Node环境逻辑正常
  • 运行所有测试:jest,确认两类测试都能正确执行

内容的提问来源于stack exchange,提问作者Dimitriy07

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 08:28:11