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

React项目用Vitest做单元测试遇JSX语法解析错误求助

解决Vitest解析JS文件中JSX的错误

问题重现

运行Vitest测试时出现以下错误:

FAIL  src/lib/tests/avatar.test.js [ src/lib/tests/simple.test.js ]
Error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
 ❯ formatError node_modules/vite/dist/node/chunks/dep-df561101.js:43993:46
 ❯ TransformContext.error node_modules/vite/dist/node/chunks/dep-df561101.js:43989:19
 ❯ TransformContext.transform node_modules/vite/dist/node/chunks/dep-df561101.js:41740:22
 ❯ Object.transform node_modules/vite/dist/node/chunks/dep-df561101.js:44283:30
 ❯ loadAndTransform node_modules/vite/dist/node/chunks/dep-df561101.js:54950:29

项目中有大量包含JSX的.js文件,无法通过重命名为.jsx解决,现有配置如下:

vitest.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  test: {
    global: true,
    environment: 'jsdom',
    setupFiles: "./src/lib/tests/setup.js",
    transform: {
      '^.+\\.jsx?$': 'esbuild-jest',
    },
  },
  plugins: [react({
    babel: {
      parserOpts: {
        plugins: ['decorators-legacy'],
      },
    },
  })]
})

setup.js

import { expect } from 'vitest';
import matchers from '@testing-library/jest-dom/matchers';

expect.extend(matchers);

组件文件 simple.js

import React from "react";

const SimpleMenu = () => {
  return <div>SimpleMenu</div>;
};

export default SimpleMenu;

测试文件 simple.test.js

import { render } from "@testing-library/react";
import { it, describe, expect } from "vitest";
import SimpleMenu from "./simple";

describe("SimpleMenu", () => {
  it("Must render correctly:", () => {
    const { container } = render(SimpleMenu);
    expect(container).toMatchSnapshot();
  });

});

package.json 依赖与脚本

"dependencies": {
    "react": "^16.14.0",
},
"scripts": {
    "test": "vitest",
    "test:coverage": "vitest run --coverage"
    "test:ui": "vitest --ui",
 },
"devDependencies": {
    "@vitejs/plugin-react": "4.0.4",
    "@vitest/coverage-v8": "0.34.3",
    "@vitest/ui": "0.34.3",
    "vite": "4.4.9",
    "vitest": "0.34.3"
 }

可行解决方案

方案1:让React插件处理所有.js文件

修改@vitejs/plugin-react的配置,添加include选项指定处理.js文件,插件会自动解析其中的JSX:

// vitest.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  test: {
    global: true,
    environment: 'jsdom',
    setupFiles: "./src/lib/tests/setup.js",
    // 移除esbuild-jest的transform配置,改用React插件处理
  },
  plugins: [react({
    include: '**/*.js', // 覆盖默认匹配规则,处理所有.js文件
    babel: {
      parserOpts: {
        plugins: ['decorators-legacy'],
      },
    },
  })]
})

方案2:配置Vitest的transform使用React插件转换器

保留transform配置,替换esbuild-jest为@vitejs/plugin-react的转换逻辑,确保JSX被正确解析:

// vitest.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  test: {
    global: true,
    environment: 'jsdom',
    setupFiles: "./src/lib/tests/setup.js",
    transform: {
      '^.+\\.js$': '@vitejs/plugin-react', // 用React插件处理.js文件
    },
  },
  plugins: [react({
    babel: {
      parserOpts: {
        plugins: ['decorators-legacy'],
      },
    },
  })]
})

方案3:修复package.json语法错误

你的package.json中scripts部分存在语法错误:"test:coverage"行末尾缺少逗号,会导致JSON解析失败,修改后:

"scripts": {
    "test": "vitest",
    "test:coverage": "vitest run --coverage",
    "test:ui": "vitest --ui"
 },

验证

修改配置后,重新运行npm run test,Vitest应能正确解析.js文件中的JSX,测试正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 20:55:57