首页 > 解决方案 > 在 VueJS 中模拟一个简单的函数,JEST

问题描述

我正在努力模拟列表组件中的删除功能。

我的测试现在看起来像这样

  describe("delete a todo", () => {
    test("should have todo removed", async () => {
      const deleteItem = jest.fn();
      const items = [{ id: 1, name: "ana", isComplete: false }];
      const wrapper = shallowMount(Todo, items);
      console.log(wrapper);
      const deleteButton = ".delete";
      wrapper.find(deleteButton).trigger("click");
      expect(deleteItem).toHaveBeenCalledWith("1");
    });

目前,当我运行测试时,错误读取。 测试错误

该应用程序工作正常,但我没有在我的测试中正确模拟删除功能,因为“新笔记”仍在通过。我究竟做错了什么?

以防万一,这是我正在测试的文件的一部分。

methods: {
    addItem() {
      if (this.newItem.trim() != "") {
        this.items.unshift({
          // id: createUID(10),
          id: uuid.v4(),
          completed: false,
          name: this.newItem
        });
        this.newItem = "";
        localStorage.setItem("list", JSON.stringify(this.items));
        this.itemsLeft = this.itemsFiltered.length;
      }
    },
    removeItem(item) {
      const itemIndex = this.items.indexOf(item);
      this.items.splice(itemIndex, 1);
      localStorage.setItem("list", JSON.stringify(this.items));
      this.itemsLeft = this.itemsFiltered.length;
    },

此外,对于更多代码,您可以从以下链接获取: https ://github.com/oliseulean/ToDoApp-VueJS

标签: javascriptvue.jsunit-testingjestjsvue-component

解决方案


我认为您必须对原始测试用例进行一些更改

  1. 将 jest.fn() 更改为 jest.spyOn(Todo.methods, 'deleteItem') 因为您必须跟踪对 Todo 组件中方法对象的调用。参考:https ://jestjs.io/docs/jest-object
  2. 等待点击事件被 await 触发
  3. 使用 toHaveBeenCalledTimes 不使用 toHaveBeenCalledWith("1")

所以你的最终测试用例看起来像这样

describe("delete a todo", () => {
    test("should have todo removed", async () => {
      const removeItem = jest.spyOn(Todo.methods, 'removeItem')
      const items = [{ id: 1, name: "ana", isComplete: false }];
      const wrapper = shallowMount(Todo, items)
      await wrapper.find('.delete').trigger('click')
      expect(removeItem).toHaveBeenCalledTimes(1);
    });
});

推荐阅读