Search code examples
unit-testingvue.jsbootstrap-vuevue-test-utils

Trigger Event on Bootstrap-Vue Component (testing)


I am writing tests in a vue app (using Jest). While testing a certain component, I need to trigger a change event on a checkbox (which I am using BFormCheckbox for).

When I select the checkbox using the selector the actual checkbox evaluates to ('.custom-control-input'), I can get the test below to pass. However, I would like to use the name of the actual component (BFormCheckbox), which I feel would be easier to follow. Is there any way to make this work?

      it('is triggered by clicking a phase checkbox', () => {
        // I would like to write:
        // const phaseCheckbox = wrapper.find(BFormCheckbox);

        // However, I can only get the following to work:
        const phaseCheckbox = wrapper.find('.custom-control-input');

        // this is true for both selectors
        expect(phaseCheckbox.exists()).toBe(true);

        phaseCheckbox.trigger('change');

        // this fails for wrapper.find(BFormCheckbox)
        expect(togglePhaseSpy).toHaveBeenCalled();
      });

Solution

  • Since the <input type="checkbox"> is nested inside additional HTML markup (as defined by Bootstrap v4), use the following to access the hidden input:

    const phaseCheckbox = wrapper.find(BFormCheckbox).find('input')
    

    This will not tie you to using the inner element classname(s), as they do change depending on the rendering style mode of <b-form-checkbox> (i.e. default custom checkbox, switch style checkbox, button style checkbox, or plain mode checkbox).