如何在 Jest 中测试 Vue 道具更新

How to test Vue prop update in Jest

我是 Jest 的新手,正在尝试为我的 Vue 应用程序编写一个测试,以确认子组件发出一个事件,结果,它的 prop 值得到更新。

作为示例,我制作了一个带有计数器的简单应用程序来演示:

/* 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>

按下 Counter 中的按钮后,它应该发出 increment 事件以增加父 Home 组件中的计数。

这是我写的测试:

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

它 returns 返回 Expected: "1" Received: "0" 表示在测试中不处理 prop 更新。我尝试结合许多资源,例如 Vue 指南 here and Vuetify unit test info here,但它总是返回相同的结果。我丢失了一块拼图,现在已经找了 2 天了。

这是一个简化的 repo 以获得更好的画面,也许可以在本地玩。

查看增量是否适用于本地数据值的测试:here,因此目前确实是 props 和 emitting 的场景让我很沮丧。任何帮助都是物有所值的!

我下载了您的存储库并进行了测试,一切正常。除了没有定义变量的标题。 见打印:https://puu.sh/GKmzu/69a9fe9f0a.png

我认为您应该只测试事件是否发出。请注意,如果您测试本地计数器,测试将通过,但不会通过 prop 计数。那是因为测试没有看到 Home 组件上的代码。请记住这是一个单元测试,目标是单独测试组件。

好的,我终于找到了解决办法!我走错了路,试图在子组件中测试父数据更改。使用我的组合(子组件 Counter 发出一个事件并触发父 Home 组件的更改),这是工作测试:


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

在“Jest”中思考的学习曲线:)