使用shallowMount挂载组件报错vm.$refs['VTU_COMPONENT']未定义
报错定位
执行shallowMount挂载App组件时抛出如下错误:
Cannot set properties of undefined (setting 'hasOwnProperty')
该错误是@vue/test-utils执行组件挂载流程时触发的,本质原因是框架内部拿不到绑定了VTU_COMPONENTref的组件实例,直接对undefined赋值属性导致崩溃。
对应框架内部触发报错的代码片段:
... var appRef = vm.$refs[MOUNT_COMPONENT_REF]; // we add `hasOwnProperty` so jest can spy on the proxied vm without throwing appRef.hasOwnProperty = function (property) { return Reflect.has(appRef, property); }; console.warn = warnSave; var wrapper = createVueWrapper(app, appRef, setProps); trackInstance(wrapper); return wrapper; ...
其中MOUNT_COMPONENT_REF常量取值为'VTU_COMPONENT',报错时vm.$refs[MOUNT_COMPONENT_REF]为undefined。
常见触发原因
- 版本依赖不匹配:Vue主版本和
@vue/test-utils版本未对应。Vue 2.x 仅兼容@vue/test-utils@1.x系列版本,Vue 3.x 仅兼容@vue/test-utils@2.x系列版本,跨主版本混用会直接导致内部挂载逻辑失效,无法获取组件ref。 - 组件渲染阶段抛出未捕获异常:复现代码中App.vue模板使用了
{{ test }}插值,但组件脚本未定义test变量,在Vue开发模式/严格模式下会直接抛出变量未定义错误,中断组件挂载流程,导致内部ref无法绑定到实例。
修复步骤
- 核对依赖版本,安装匹配的
@vue/test-utils版本:
先执行命令查看本地已安装的版本:
Vue2项目执行安装适配版本:npm list vue @vue/test-utils
Vue3项目执行安装适配版本:npm install -D @vue/test-utils@latest-v1npm install -D @vue/test-utils@latest - 修复组件语法错误,要么移除模板中未定义的
test变量引用,要么在组件中声明对应变量:<template> <div id="a-test"> {{ test }} </div> </template> <script> export default { name: "App", data() { return { test: "" } } }; </script> - 若上述操作后仍报错,可在挂载时添加
attachTo配置,确保组件渲染完成ref绑定:import { shallowMount } from "@vue/test-utils"; import App from "@/App"; describe("App.vue", () => { test("Test that fails", async () => { const wrapper = shallowMount(App, { attachTo: document.body }); }); });
内容的提问来源于stack exchange,提问作者snoob dogg
相关产品推荐
相关产品推荐

