Jest / Vue 测试实用程序 - 来自子组件作用域插槽的方法 - [Vue 警告]:事件 "click" 的无效处理程序:未定义

Jest / Vue test utils - Method coming from subcomponent scoped slot - [Vue warn]: Invalid handler for event "click": got undefined

我正在尝试测试调用子组件的组件之一(即 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 子组件没有完全挂载(stub,shallowMount)并且 close() 方法没有被注入。

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

感谢您的帮助!

您可以自定义 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()
})