【问题标题】:How to test Vue prop update in Jest如何在 Jest 中测试 Vue 道具更新
【发布时间】:2021-02-18 07:45:16
【问题描述】:

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

它返回为Expected: "1" Received: "0",表示在测试中未处理道具更新。我尝试结合许多资源,例如 Vue 指南 here 和 Vuetify 单元测试信息 here,但它始终保持不变。我错过了一块拼图,现在已经找了 2 天了。

这是一个简化的repo 以获得更好的图片,也许可以在本地播放。

一个测试,看看增量是否适用于本地数据值工作正常:here,所以这真的是道具和发射的场景让我现在很沮丧。任何帮助都物超所值!

【问题讨论】:

    标签: unit-testing vue.js jestjs vuetify.js vue-test-utils


    【解决方案1】:

    好的,我终于找到了解决办法!我在事情上走错了路,并试图测试子组件中的父数据更改。使用我的组合(子组件 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);
      });
    

    学习曲线以“玩笑”思考:)

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢你!对父组件(Home)进行单元测试,在测试中找出子组件(Counter),触发子组件的emit,然后检查Home中的数据值是否因此改变?
      【解决方案3】:

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

      【讨论】:

      • 感谢您注意到这一点!对标题错误感到抱歉,忘记从简化版本中删除它,但现在在home 中修复它。澄清一下,在运行 npm run test 后,前 2 次测试对您来说都是阳性的?你能不能做一个测试终端的截图? (您链接的那个来自浏览器)
      • 执行npm run test确实有错误见截图:puu.sh/GKpIk/75c60c8dd8.png
      • 是的,这和我的结果一样,这就是我制作这张票的原因
      猜你喜欢
      • 2018-05-08
      • 2018-01-10
      • 2021-07-05
      • 2020-02-25
      • 1970-01-01
      • 2019-05-01
      • 2020-08-04
      • 2020-12-21
      • 1970-01-01
      相关资源
      最近更新 更多