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

Vue3+Vite3中unplugin-vue-define-options报错及Vitest模拟请求问题

一、在Vue.js中使用Vitest模拟HTTP请求的测试方案

针对axios的模拟测试

如果项目使用axios发起HTTP请求,可通过vi.mock()直接模拟axios模块:

  1. 示例组件(UserList.vue):
<script setup>
import axios from 'axios'
const { data: users } = await axios.get('/api/users')
</script>
<template>
  <ul>
    <li v-for="user in users" :key="user.id">{{ user.name }}</li>
  </ul>
</template>
  1. 对应测试文件(UserList.test.ts):
import { mount } from '@vue/test-utils'
import axios from 'axios'
import UserList from './UserList.vue'

// 模拟axios.get方法的返回值
vi.mock('axios', () => ({
  get: vi.fn().mockResolvedValue({
    data: [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' }
    ]
  })
}))

test('渲染用户列表', async () => {
  const wrapper = mount(UserList)
  // 等待异步请求完成
  await wrapper.vm.$nextTick()
  // 验证列表渲染结果
  expect(wrapper.findAll('li')).toHaveLength(2)
  // 检查axios.get是否被正确调用
  expect(axios.get).toHaveBeenCalledWith('/api/users')
})

针对原生fetch的模拟测试

如果使用原生fetch,可直接模拟全局fetch对象:

test('通过fetch请求渲染数据', async () => {
  // 模拟fetch的返回逻辑
  global.fetch = vi.fn().mockResolvedValue({
    json: vi.fn().mockResolvedValue([{ id: 1, name: 'Charlie' }])
  })

  const wrapper = mount(UserList)
  await wrapper.vm.$nextTick()

  expect(global.fetch).toHaveBeenCalledWith('/api/users')
  expect(wrapper.text()).toContain('Charlie')
})

关键注意事项

  • 异步测试必须搭配async/await,并通过$nextTick()或waitFor()等待请求完成
  • 若只需模拟模块的某个方法,可使用vi.spyOn()替代全量的vi.mock()

二、解决unplugin-vue-define-options的scriptSetupAst未定义错误

出现TypeError: Cannot read properties of undefined (reading 'scriptSetupAst'),核心原因是版本不兼容或配置顺序错误,按以下步骤排查:

  1. 匹配对应版本
    Vite 3需搭配特定版本的unplugin-vue-define-options,建议安装适配版本:
npm uninstall unplugin-vue-define-options
npm install unplugin-vue-define-options@0.11.5

同时确保Vue版本为3.2.x及以上(script setup语法的最低要求)

  1. 调整插件注册顺序
    在vite.config.ts中,必须将unplugin-vue-define-options放在@vitejs/plugin-vue之前注册:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import DefineOptions from 'unplugin-vue-define-options/vite'

export default defineConfig({
  plugins: [
    DefineOptions(), // 先注册此插件
    vue()
  ]
})
  1. 清除缓存并重装依赖
  • 删除node_modules、package-lock.json(或yarn.lock)文件
  • 重新执行npm install
  • 重启Vite开发服务
  1. 检查script setup语法
    确保组件中的<script setup>标签无语法错误(如未闭合、非法语句),错误的脚本代码会导致插件无法正确解析AST结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:55:22