Search code examples
vue.jsvuejs2jestjsbootstrap-vuevue-test-utils

How to test that a Vue directives is called on hover/mouseover?


I try to test that theb-tooltip.hover directive from bootstrap-vue is called on hover. It seems that the directive is called even without triggering the hover event andbuttonWrapper.trigger('mouseover'); doesn't show any effect.

How can I trigger the hover event correctly?

The simplified Vue component ButtonWithTooltip.vue which I try to test:

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

The unit test which passes successfully although the line is commented which triggers the hover event:

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'
    });
  });
});

Solution

  • UPDATED

    From comments below:

    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)
    

    OLD

    Try to test it by checking html content, e.g.:

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

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

    Or maybe (not sure):

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

    Do not forget to remove any mocks, e.g.:

    directives: { 'b-tooltip': BTooltipDirective }