【问题标题】:How to test that a Vue directives is called on hover/mouseover?如何测试在悬停/鼠标悬停时调用了 Vue 指令?
【发布时间】:2020-01-19 02:25:34
【问题描述】:

我尝试测试来自bootstrap-vueb-tooltip.hover 指令在悬停时被调用。 似乎即使没有触发悬停事件也调用了该指令,并且buttonWrapper.trigger('mouseover'); 没有显示任何效果。

如何正确触发悬停事件?

我尝试测试的简化的Vue组件ButtonWithTooltip.vue

<template>
  <b-btn v-b-tooltip.hover="{ title: 'someText'}">Button with Tooltip</b-btn>
</template>

虽然注释了触发悬停事件的行但成功通过的单元测试:

import { createLocalVue, mount } from '@vue/test-utils';
import BootstrapVue from 'bootstrap-vue';
import ButtonWithTooltip from '@/components/ButtonWithTooltip.vue';

const localVue = createLocalVue();
localVue.use(BootstrapVue);
localVue.use(ButtonWithTooltip);

describe('ButtonWithTooltip.vue', () => {
  it('shows tooltip on hover over the button', () => {
    const BTooltipDirective = jest.fn();
    const wrapper = mount(ButtonWithTooltip, {
      localVue,
      directives: { 'b-tooltip': BTooltipDirective }
    });

    const buttonWrapper = wrapper.find('button');
    expect(buttonWrapper.exists()).toBe(true);

    // buttonWrapper.trigger('mouseover'); <--- test is passed successfully even without this line

    expect(BTooltipDirective).toHaveBeenCalled();
    expect(BTooltipDirective.mock.calls[0][1].value).toEqual({
      title: 'someText'
    });
  });
});

【问题讨论】:

标签: vue.js vuejs2 jestjs bootstrap-vue vue-test-utils


【解决方案1】:

更新

来自下面的cmets:

expect(buttonWrapper.attributes('aria-describedby')).toBeDefined()
const adb = buttonWrapper.attributes('aria-describedby')

const tip = document.querySelector(`#${adb}`)
expect(tip).not.toBe(null)
expect(tip.classList.contains('tooltip')).toBe(true)

尝试通过检查html内容来测试它,例如:

buttonWrapper.trigger('mouseover');
expect(wrapper.contains("someText')).toEqual(true);

https://vue-test-utils.vuejs.org/api/wrapper/contains.html

或者也许(不确定):

expect(wrapper.find("BTooltip').isVisible()).toEqual(true);

不要忘记删除任何模拟,例如:

directives: { 'b-tooltip': BTooltipDirective }

【讨论】:

  • 不幸的是,这不起作用,因为工具提示的渲染 DOM 不是包装器的一部分。而是附加到页面底部的 DOM
  • 如果您通过浏览器 api 检查会怎样,例如document.querySelector('.b-tooltip') != null。我已经检查了文档中的示例,我看到当您将鼠标悬停在元素上时,将添加具有 b-tooltip 类的元素。可能你必须使用attachToDocument 选项
  • 您可以查看 BootstrapVue 如何测试工具提示指令:github.com/bootstrap-vue/bootstrap-vue/blob/dev/src/directives/…
  • @TroyMorehouse 谢谢你,它实际上回答了我的问题
猜你喜欢
  • 1970-01-01
  • 2017-03-06
  • 2011-08-04
  • 2018-09-03
  • 2018-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多