首页 > 解决方案 > [Vue 警告]:挂载钩子错误:“TypeError:this.$refs.appConfirm.setCellphone 不是函数”

问题描述

我在尝试模拟 vue 中的引用时出错,因为我找到的解决方案使用了存根。但是存根只接受字符串。

it("Test component", () => {
  const wrapper = mount(NeedConfirmation, {
    localVue,
    store
  });
});

[Vue 警告]:挂载钩子错误:“TypeError:this.$refs.appConfirm.setCellphone 不是函数”

it("Test component", () => {
  const appConfirm = {
    setCellphone: () => {}
  };
  const wrapper = mount(NeedConfirmation, {
    localVue,
    store,
    stubs: {
      appConfirm
    }
  });
});

[vue-test-utils]:options.stub 值必须传递一个字符串或组件

标签: vue.jsjestjsvue-test-utils

解决方案


对于自定义存根组件,提供组件定义stubs,例如,通过导入'*.vue'文件或使用 Vue 选项 API 定义组件对象。

以下示例定义了 Vue 2 1️⃣ 中的组件内联,并验证setCellphone在挂载 2️⃣ 后调用该组件:

import NeedConfirmation from '@/components/NeedConfirmation.vue'
import { mount } from '@vue/test-utils'

it('Test component', () => {
  const setCellphone = jest.fn()

  const wrapper = mount(NeedConfirmation, {
    stubs: {
      // 1️⃣
      appConfirm: {
        template: `<div></div>`,
        methods: {
          setCellphone
        }
      }
    }
  })

  // wait for refs to resolve in `mount()`...
  await wrapper.vm.$nextTick()

  // 2️⃣
  expect(setCellphone).toHaveBeenCalled()
})

推荐阅读