unit-testingvue.jsjestjsvuetify.jsvue-test-utils

How to test Vue prop update in Jest


I'm new to Jest and trying to write a test for my Vue app that would confirm a child component emits an event and as a result, its prop value gets updated.

As an example I've made a simple app with a counter to demonstrate:

/* Parent Home.vue */
<template>
  <Counter :count="count" @increment="count++"/>
</template>

<script>
import Counter from "@/components/Counter.vue";
export default {
  components: { Counter },
  data: () => ({
    count: 0,
  }),
};
</script>
/* Child Counter.vue */
<template>
  <v-container>
    <div id="propTracker">{{ count }}</div>
    <v-btn ref="incrementProp" @click="increment($event)">Increase prop</v-btn>
  </v-container>
</template>

<script>
export default {
  props: ["count"],
  methods: {
    increment() {
      this.$emit("increment");
    },
  },
};
</script>

Once the button in Counter is pressed, it should emit an increment event to increment the count in parent Home component.

This is the test I've written:

  it("Click should increment count text", async () => {
    const wrapper = mount(Counter, {
      localVue,
      vuetify,
      propsData: { count: 0 },
    });

    expect(wrapper.find("#propTracker").text()).toBe("0"); //initial state

    const button = wrapper.find({ ref: "incrementProp" });
    await button.trigger("click"); //trigger click

    expect(wrapper.find("#propTracker").text()).toBe("1"); //after click
  });

It returns back as Expected: "1" Received: "0" indicating that the prop update is not processed within the test. I've tried to combine many resources such as Vue guidelines here and Vuetify unit test info here, yet it keeps coming back the same. I'm missing a puzzle piece and been looking for it for 2 days now.

This is a simplified repo to have a better picture and perhaps play around locally.

A test to see if incrementing works with local data values worked fine: here, so it's really the scenario with props and emitting that bums me out at the moment. Any help would be worth its weight in gold!


Solution

  • Okay, I finally found a solution! I went the wrong way about things and tried to test parent data changes in a child component. With the composition I have (child component Counter emits an event and triggers a change in parent Home component), this is the working test:

    
      it("Counter button changes count in Home", () => {
        const wrapper = mountFactory(Home);
    
        //check if initial count in Home is 0
        expect(wrapper.vm.count).toBe(0);
    
        //click btn in Counter (child component)
        wrapper.find("#incrementBtn").trigger("click");
    
        //check if increment worked and count has increased
        expect(wrapper.vm.count).toBe(1);
      });
    

    Learning curve to think in "Jest" :)