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

使用Vitest进行Vue单元测试时遇模板/脚本缺失错误排查

Vue Vitest单元测试报模板/脚本缺失错误的排查与临时解决

问题现象

执行Vue组件单元测试时,Vitest抛出如下错误:

FAIL  tests/unit/components/MyComponent.spec.js [ tests/unit/components/MyComponent.spec.js ]
SyntaxError: At least one <template> or <script> is required in a single file component.

实际组件代码中已包含<template>和<script>标签,且组件能在网页正常渲染,排除组件本身问题后,锁定为Vitest配置异常导致。

出现问题的Vitest配置

export default mergeConfig(
  viteConfig,
  defineConfig({
    plugins: [Vue()],
    test: {
      globals: true,
      environment: 'jsdom',
      exclude: [...configDefaults.exclude, 'e2e/*', 'packages/template/*'],
      root: fileURLToPath(new URL('./', import.meta.url)),
      transformMode: {
        web: [/\.[jt]sx$/]
      }
    },
    root: '.'
  })
)

临时解决方案

移除配置中plugins数组内的Vue()插件,修改后配置如下:

export default mergeConfig(
  viteConfig,
  defineConfig({
    plugins: [], // 移除Vue()
    test: {
      globals: true,
      environment: 'jsdom',
      exclude: [...configDefaults.exclude, 'e2e/*', 'packages/template/*'],
      root: fileURLToPath(new URL('./', import.meta.url)),
      transformMode: {
        web: [/\.[jt]sx$/]
      }
    },
    root: '.'
  })
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 00:02:38