在 VueJS 中模拟一个简单的函数,JEST

Mocking a simple function in 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");
    });

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

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

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

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

另外,更多代码,你可以从下面link获取: https://github.com/oliseulean/ToDoApp-VueJS

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

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