【问题标题】:[Vue warn]: Error in mounted hook: "TypeError: this.$refs.appConfirm.setCellphone is not a function"[Vue 警告]:挂载钩子错误:“TypeError:this.$refs.appConfirm.setCellphone 不是函数”
【发布时间】:2021-03-07 15:46:53
【问题描述】:

我在尝试模拟 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.js jestjs vue-test-utils


    【解决方案1】:

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

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

    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()
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-23
      • 2020-07-03
      • 2022-01-03
      • 2020-10-12
      • 2020-12-22
      • 2020-10-04
      • 2020-10-03
      • 1970-01-01
      相关资源
      最近更新 更多