1

I have the following Vue component:

<template>
    <div>
        <div>
            <year-btn @click="incrementYear"
                ref="increment-btn"/>
        </div>
    </div>
</template>

<script>
import yearBtn from "@/components/formInputs/yearBtn.vue";

export default {
    components: {
        "year-btn": yearBtn,
    },
    data() {
        return {
            monthAndYear: {
                year: 2000,
            },
        };
    },
    methods: {
        incrementYear() {
            this.monthAndYear.year++;
        },
    },
};
</script>

And I have the following Vue unit test.

it('test', async () => {
    wrapper = factory();

    wrapper.setData({
        monthAndYear: {
            year: 2020,
        },
    });

    wrapper.find({ ref: "increment-btn" }).trigger("click");
    await wrapper.vm.$nextTick();

    result = wrapper.vm.monthAndYear.year;
    expect(result).toEqual(2021);
});

Unfortunately, the above test fails because the click event on the 'year-btn' component fails to be triggered by Vue Test Utils. I know this because, if I replace my template with the following code the test passes.

<template>
    <div>
        <div>
            <button @click="incrementYear"
                ref="increment-btn"></button>
        </div>
    </div>
</template>

My question is, how do I trigger a "click" event on a child component (year-btn) that my component is using?

Below is what the year-btn component looks like:

<template>
    <button @click="$emit('click')">
        Click me
    </button>
</template>
1
  • @tony19 its at the bottom of my post - all it does is emit a click event when there is a click on the button. Commented Mar 9, 2020 at 9:13

2 Answers 2

2

Seems likely that factory() is using shallowMount, which stubs its child components. Switch to mount to ensure the YearBtn is actually rendered.

Sign up to request clarification or add additional context in comments.

Comments

2

If you add console.log to incrementYear you will see that ref holds component object not DOM element.

    incrementYear() {
      this.monthAndYear.year++;
      console.log(this.$refs['increment-btn'])
    },

So try to change this:

wrapper.find({ ref: "increment-btn" }).trigger("click");

to this:

wrapper.find({ ref: "increment-btn" }).$el.trigger("click");

3 Comments

Didn't work unfortunately. I get TypeError: Cannot read property 'trigger' of undefined when the test is run.
Great answer ^^ N.B. Vue is deprecating wrapper.find in favour of wrapper.findComponent if anyone else stumbles across this.
@SRack Only for finding components specifically. wrapper.find is still applicable for finding DOM elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.