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

使用Vitest测试含v-dialog的Vue组件时抛出TypeError: globalStack.at is not a function

解决Vuetify 3 + Vitest测试v-dialog时的globalStack.at is not a function错误

问题重现

在集成Vuetify 3和Vitest的Vue 3项目中,使用happy-dom(v8.1.1)或jsdom(v20.0.3)运行单元测试时,只要组件包含<v-dialog>,就会抛出以下错误:

TypeError: globalStack.at is not a function
    at ......./node_modules/vuetify/src/composables/stack.ts:58:3
    ...(后续调用栈省略)

使用shallowMount测试可正常运行,但使用mount测试对话框功能时触发报错;浏览器端升级Chrome后该问题消失,但测试环境仍存在。

根因分析

Array.prototype.at()是ES2022新增的数组方法,Vuetify内部的stack.ts依赖该方法实现栈操作。但当前使用的测试环境DOM模拟库(happy-dom@8.1.1、jsdom@20.0.3)未全局实现该方法,导致运行时抛出错误。浏览器端升级后正常是因为新版Chrome已原生支持ES2022特性。

解决方法

方法1:升级测试环境DOM库

升级happy-dom或jsdom到支持Array.prototype.at()的版本:

# 升级happy-dom到最新版
npm install happy-dom@latest --save-dev

# 或者升级jsdom到最新版
npm install jsdom@latest --save-dev

升级后修改vite.config.js中test.environment为对应的库(比如happy-dom或jsdom),重新运行测试即可。

方法2:手动添加Array.prototype.at()的Polyfill

若暂时无法升级DOM库,可在测试前置文件中添加polyfill。修改vuetify.config.js:

global.CSS = { supports: () => false };

// Polyfill ES2022的Array.prototype.at方法
if (!Array.prototype.at) {
  Array.prototype.at = function(index) {
    index = Math.trunc(index) || 0;
    if (index < 0) index += this.length;
    if (index < 0 || index >= this.length) return undefined;
    return this[index];
  };
}

该polyfill实现了at()方法的核心逻辑,能让测试环境识别并正常调用。

方法3:升级Vuetify到兼容版本

升级Vuetify到后续修复版本(比如3.1.x及以上),新版本可能已兼容低版本DOM模拟库,或替换了at()的使用方式:

npm install vuetify@latest --save

验证

修改完成后,重新运行测试:

npx vitest run

确认使用mount测试含<v-dialog>的组件时不再报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:35:51