Avocado
Avocado

Reputation: 901

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

Upvotes: 1

Views: 1821

Answers (2)

Troy Morehouse
Troy Morehouse

Reputation: 5435

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).

Upvotes: 2

Jesus Galvan
Jesus Galvan

Reputation: 576

Jest documentation shows examples of how to do as you are asking.

Component Constructors:

import Foo from '../components/Foo';

const wrapper = mount(<MyComponent />);
expect(wrapper.find(Foo)).to.have.lengthOf(1);

Component Display Name:

const wrapper = mount(<MyComponent />);
expect(wrapper.find('Foo')).to.have.lengthOf(1);

Upvotes: 1

Related Questions