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

Vite应用测试报错“Error: Expression expected”求助

Vite应用测试报错“Error: Expression expected”排查

问题

在Vite项目里运行Vitest测试时,直接抛出“Error: Expression expected”错误导致测试失败。试过更换getByPlaceholderText等不同匹配器和属性,错误依然存在。

测试代码(sum.test.js)

/* eslint-disable no-undef */
import React from 'react';
import { render, screen } from '@testing-library/react';

function InputComponent() {
    return <input type="text" name="userName" />;
}

test('renders input with aria-label', () => {
    render(<InputComponent />);
    const inputElement = screen.getByRole('textbox');
    expect(inputElement).toBeInTheDocument();
});

控制台报错信息

FAIL  sum.test.js [ sum.test.js ]
Error: Expression expected
 ❯ getRollupError ../../../.nvm/versions/node/v20.5.0/lib/node_modules/vitest/node_modules/rollup/dist/es/shared/parseAst.js:396:41

 Test Files  1 failed (1)
      Tests  no tests
   Start at  15:08:31
   Duration  0ms

可能的原因及解决方法

  • JSX转译配置缺失:Vitest默认不会自动处理React的JSX语法。需要在项目的vitest.config.js或vite.config.js中配置@vitejs/plugin-react插件,确保JSX被正确转译。
  • 环境依赖不兼容:Node.js v20.5.0可能与当前Vitest版本存在兼容性问题。建议降级到Node.js LTS版本(如v18.x),或者升级Vitest到最新稳定版。
  • 测试环境未配置JS DOM:测试React组件需要JS DOM环境。确保已安装jsdom依赖,并在Vitest配置中设置test: { environment: 'jsdom' }。
  • Rollup解析异常:报错来自Rollup的AST解析环节,虽然提供的代码语法正常,但可能是配置导致Rollup无法正确识别JSX。检查Vitest的Rollup相关配置,确保React插件已启用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:24:58