简体   繁体   English

Mocking 一个简单的 function 在 VueJS,JEST

[英]Mocking a simple function in VueJS, JEST

I am struggling to mock the delete function in the lists component.我正在努力模拟列表组件中的删除 function 。

My test looks like this at the moment我的测试现在看起来像这样

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

currently, when I run the tests the error reads.目前,当我运行测试时,错误读取。 Test Error测试错误

The application works fine, but I am not mocking the delete function correctly in my test as a "New Note" is still being passed through.该应用程序工作正常,但我不是 mocking 删除 function 在我的测试中正确,因为“新注释”仍在通过。 What am I doing wrong?我究竟做错了什么?

just in case it helps, here is a part of the file I am testing.以防万一,这是我正在测试的文件的一部分。

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

Also for more code, you can get it from the following link: https://github.com/oliseulean/ToDoApp-VueJS此外,有关更多代码,您可以从以下链接获取: https://github.com/oliseulean/ToDoApp-VueJS

I think you have to make some changes to your original test case我认为您必须对原始测试用例进行一些更改

  1. Change jest.fn() to jest.spyOn(Todo.methods, 'deleteItem') since you have to track calls to methods object in Todo component.将 jest.fn() 更改为 jest.spyOn(Todo.methods, 'deleteItem') 因为您必须在 Todo 组件中跟踪对方法 object 的调用。 Refer: https://jestjs.io/docs/jest-object参考: https://jestjs.io/docs/jest-object
  2. Wait for the click event to be triggered with await等待点击事件被 await 触发
  3. Use toHaveBeenCalledTimes not toHaveBeenCalledWith("1")使用 toHaveBeenCalledTimes 不使用 toHaveBeenCalledWith("1")

So your final test case will look like this所以你的最终测试用例看起来像这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM