【问题标题】:How do I test if a Vue method was called using Jest?如何测试是否使用 Jest 调用了 Vue 方法?
【发布时间】:2021-09-06 14:58:04
【问题描述】:

我正在尝试进行测试,看看是否在按下按钮时调用了我的 Vue 应用程序中的方法。主应用中的相关代码(使用Quasar组件和类)为:

<template>
   <div class="row justify-center inputs">
      <q-input label="Item" v-model="newitem" class="inputbox" outlined></q-input>
      <q-input type="number" label="Quantity" v-model="quantity" class="input2" color="secondary" outlined></q-input>
      <q-btn color="primary" @click="appenditem" class="submit" :disabled="quantity < 1 || newitem.length < 1" no-caps>Add Item</q-btn>
   </div>
</template>

<script>
export default {
  name: 'LayoutDefault',
  components: {
  },
  data () {
    return {
      newitem: "",
      quantity: null,
      array: [],
    }
  },
   methods: {
    appenditem: function() {
          this.array.push({text: this.newitem, quantity: this.quantity});
          this.quantity = null;
          this.newitem = "";
    },
  }
}
</script>

在我的测试代码中,我有:

import App from "@/App.vue";
import {shallowMount} from "@vue/test-utils";
describe("input-field.vue", () => {
    const wrapper = shallowMount(App);
    const append = jest.spyOn(App.methods, "appenditem");
    it("renders", () => {
        expect(wrapper.exists()).toBe(true);
    });
    it("title is correct", () => {
        expect(wrapper.find("h1").text()).toBe("Inventory Manager")
    });
    it("input field loads correctly", () => {
        expect(wrapper.vm.$data.newitem).toBe("")
    });
    it("add button works", () => {
        wrapper.find(".submit").trigger("click");
        expect(append).toHaveBeenCalled();
    })
})

据我所知,变量append 应该监视适当的函数,然后测试应该检查在单击具有类submit 的元素时是否调用了该函数。当我运行测试时,它失败了,我得到了输出:

expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      15 |      it("add button works", () => {
      16 |              wrapper.find(".submit").trigger("click");
    > 17 |              expect(append).toHaveBeenCalled();
         |                             ^
      18 |      })
      19 | })

我在这里缺少什么?我知道该函数正在被调用,因为该程序有效。

任何帮助将不胜感激:)

【问题讨论】:

    标签: vue.js testing jestjs


    【解决方案1】:

    click-handler 在下一次调用中被调用,所以你的测试应该await trigger("click") 调用:

    it("add button works", async () => {
      await wrapper.find(".submit").trigger("click");
      expect(append).toHaveBeenCalled();
    })
    

    【讨论】:

      猜你喜欢
      • 2019-01-25
      • 2019-07-24
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多