【问题标题】:Jest / Vue test utils - Method coming from subcomponent scoped slot - [Vue warn]: Invalid handler for event "click": got undefinedJest / Vue 测试实用程序 - 来自子组件范围插槽的方法 - [Vue 警告]:事件“点击”的无效处理程序:未定义
【发布时间】:2021-10-02 15:03:32
【问题描述】:

我正在尝试测试我的一个调用子组件的组件(即b-modal)。

我测试的组件使用来自b-modal 的作用域槽从其中获取close() 方法并将其附加到另一个事件侦听器。看看:

// My custom parent component
<template>
    <b-modal>
        <template #modal-header="{close}">
            <h2 class="card-header-title">
                Coordonnées
            </h2>
            <button class="close close-profile text-dark" @click="close">
                <i class="far fa-times" />
            </button>
        </template>
    </b-modal>
</template>

在我的测试中,我像这样安装我的组件:

return shallowMount(MyCustomParentComponent, {
    ...options,
    localVue,
    store,
    stubs: [
        "b-modal"
    ],
});

我的测试通过了,但 Jest 抛出 console.error 警告:

[Vue warn]: Invalid handler for event "click": got undefined
      
      found in
      
      ---> <Anonymous>
             <Root>
      

我猜我的b-modal 子组件没有完全挂载(存根、浅层)并且close() 方法没有注入。

我能做什么?我应该模拟close() 方法吗?无声的警告?还有什么?

感谢您的帮助!

【问题讨论】:

  • 你试过用mount代替shallowMount吗?
  • 是的,mount 或 shallowmount 没有任何区别。它们都需要存根来渲染 b-modal 子组件,并且在这两种情况下,都缺少 close 方法。

标签: vue.js testing jestjs vue-test-utils slots


【解决方案1】:

您可以自定义b-modal 的存根,使用模拟的close() 渲染modal-header 插槽:

it('should call close() on button click', async () => {
  const close = jest.fn()
  const ok = jest.fn()
  const cancel = jest.fn()
  const wrapper = shallowMount(MyModal, {
    stubs: {
      BModal: {
        render(h) {
          return h('div', [
                            this.$scopedSlots['modal-header']?.({close}),
                            this.$scopedSlots['default']?.({ok, cancel})
                          ]
                  )
        }
      }
    }
  });
  await wrapper.find('button.close').trigger('click')
  expect(close).toHaveBeenCalled()
})

【讨论】:

    猜你喜欢
    • 2018-09-11
    • 2021-05-05
    • 2017-04-04
    • 2021-02-05
    • 2020-01-27
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    相关资源
    最近更新 更多