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

React/TypeScript项目中Jest测试报ReferenceError: tsx is not defined

解决Jest测试中的tsx is not defined错误

问题描述

在React+TypeScript项目中编写Jest测试时,test目录下的test.tsx运行报错ReferenceError: tsx is not defined。测试代码如下:

import React from 'react';

describe('Test', () => {
    test('Test', () => {
        let div = <div></div>;
        console.log(div);
    })
});

错误信息:

ReferenceError: tsx is not defined

      3 | describe('Test', () => {
      4 |     test('Test', () => {
    > 5 |         let div = <div></div>;
        |                   ^
      6 |         console.log(div);
      7 |     })
      8 | });

现有配置文件

tsconfig.json(必须保留jsx: "react"和jsxFactory: "tsx")

{
    "compilerOptions": {
        "module": "esnext",
        "target": "es6",
        "sourceMap": false,
        "jsx": "react",
        "jsxFactory": "tsx",
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "preserveConstEnums": true,
        "skipLibCheck": true,
        "lib": [
            "dom",
            "esnext"
        ],
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "allowJs": true
    },
    "include": [
        "src"
    ],
    "exclude": [
        "node_modules",
        "reports",
        "test"
    ]
}

jest.config.json

{
    "testEnvironment": "jsdom",
    "reporters": [
        "default",
        "jest-junit"
    ],
    "collectCoverage": true,
    "coverageDirectory": "reports",
    "coverageReporters": [
        "text",
        "cobertura"
    ],
    "collectCoverageFrom": [
        "**/*.{js,jsx,ts,tsx}",
        "!**/node_modules/**",
        "!**/test/**",
        "!**/dist/**"
    ],
    "transform": {
        "^.+\\.ts[x]?$": [
            "ts-jest",
            {
                "isolatedModules": true
            }
        ]
    },
    "displayName": {
        "name": "Report",
        "color": "blue"
    },
    "modulePathIgnorePatterns": [
        "<rootDir>/dist"
    ],
    "transformIgnorePatterns": [
        "node_modules"
    ],
    "moduleNameMapper": {
        "\\.(css)$": "<rootDir>/test/__mocks__/styles.js"
    }
}

package.json 开发依赖

"devDependencies": {
    "@types/jest": "^29.5.11",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^14.0.0",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.9.0",
    "jest": "^29.7.0",
    "ts-jest": "29.1.1",
    "jest-junit": "16.0.0",
    "jest-environment-jsdom": "^29.7.0",
    "style-loader": "^3.3.4",
    "typescript": "~4.9.4",
    "ts-loader": "^9.5.1",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4"
  },

解决方案

原因分析

tsconfig.json中指定了jsxFactory: "tsx",TypeScript会将JSX语法编译为tsx(<div>)而非默认的React.createElement(<div>)。但测试代码中仅导入了React,未定义tsx变量,且主tsconfig.json排除了test目录,导致测试代码未被正确配置处理,从而报错。

方案1:修改测试文件,显式导入/定义tsx

如果项目中tsx是React.createElement的别名,可在测试文件中直接重命名导入:

import React, { createElement as tsx } from 'react';

describe('Test', () => {
    test('Test', () => {
        let div = <div></div>;
        console.log(div);
    })
});

方案2:为测试目录单独配置TypeScript

  1. 新建tsconfig.test.json,继承主配置并包含测试目录:
{
  "extends": "./tsconfig.json",
  "include": ["test"],
  "exclude": ["node_modules", "reports", "dist"]
}
  1. 修改jest.config.json中的ts-jest配置,指定测试用的tsconfig,并全局映射tsx到React.createElement:
"transform": {
  "^.+\\.ts[x]?$": [
    "ts-jest",
    {
      "isolatedModules": true,
      "tsconfig": "./tsconfig.test.json",
      "globals": {
        "tsx": "React.createElement"
      }
    }
  ]
}

方案3:全局注入tsx变量

  1. 新建测试初始化文件test/setup.ts:
import React from 'react';
global.tsx = React.createElement;
  1. 在jest.config.json中添加初始化配置:
"setupFilesAfterEnv": ["<rootDir>/test/setup.ts"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:45:31