如何测试是否使用 Jest 调用了 Vue 方法?

时间:2021-06-23 03:50:06

标签: vue.js testing jestjs

我正在尝试进行测试,看看我的 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 | })

我在这里错过了什么?我知道正在调用该函数是因为该程序有效。

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:0)

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

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