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

Jest测试Next.js组件遇ts(2749)错误求助

解决Next.js + Jest测试中ts(2749)类型错误

问题场景

使用Jest测试Next.js组件时,调用render(<Home />)触发TypeScript错误:

'Home' is being referenced as a value, but is being used as a type here. Would you like to use 'typeof Home' instead? ts(2749)

已在jest.config.ts中配置moduleNameMapper,但问题未解决。

相关配置文件

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts",
    "./jest.setup.js",
    "jest.config.js"
  ],
  "exclude": ["node_modules"]
}
// eslintrc.json
{
  "plugins": ["jsx-a11y", "@typescript-eslint", "prettier", "jest"],
  "env": {
    "browser": true,
    "node": true,
    "es6": true,
    "jest/globals": true,
    "jest": true
  },
  "ignorePatterns": [
    "node_modules/",
    ".eslintrc.js",
    "next.config.js",
    "postcss.config.js",
    "run_server.js",
    "jest.config.ts"
  ]
}
// jest.config.ts
import type { Config } from "jest";
import nextJest from "next/jest.js";

const createJestConfig = nextJest({
  dir: "./",
});
const config: Config = {
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/$1",
  },
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8",
};

export default createJestConfig(config);
// ./__tests__/Home.test.ts
import { render } from "@testing-library/react";
import Home from "@/app/page";

test("", () => {
  render(<Home />); // 触发ts(2749)错误
});

原因及解决方案

错误核心是Home被识别为TypeScript类型而非可执行的React组件值,按以下步骤排查修复:

  • 确认页面组件的导出方式
    检查@/app/page.tsx(或page.ts)的代码,确保是默认导出React组件值,而非仅导出类型:

    // app/page.tsx
    export default function Home() {
      return <div>Home Page</div>;
    }
    

    若仅导出export type Home = ...这类类型定义,会导致无法作为JSX元素使用。

  • 更新TypeScript配置的include范围
    在tsconfig.json的include数组中添加测试文件路径,确保TS能识别测试文件中的类型:

    "include": [
      // 原有内容
      "__tests__/**/*.ts",
      "__tests__/**/*.tsx"
    ]
    
  • 验证Jest配置的完整性
    确保nextJest预设正确包裹配置,它会自动处理Next.js App Router的组件导入规则,无需额外修改moduleNameMapper之外的配置。

  • 处理异步页面组件
    若Home是包含async/await的Server Component,需用异步测试逻辑适配:

    test("renders async home page", async () => {
      const { findByText } = render(<Home />);
      await findByText("目标文本");
    });
    
  • 清除Jest缓存
    运行jest --clearCache后重新执行测试,避免缓存导致的类型识别异常。

内容的提问来源于stack exchange,提问作者이준희

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:13:13