【问题标题】:Mocking a simple function in VueJS, JEST在 VueJS 中模拟一个简单的函数,JEST
【发布时间】:2021-03-16 12:17:38
【问题描述】:

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

我现在的测试是这样的

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

还可以从以下链接获取更多代码: https://github.com/oliseulean/ToDoApp-VueJS

【问题讨论】:

    标签: javascript vue.js unit-testing jestjs vue-component


    【解决方案1】:

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

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

    【讨论】:

    • 我仍然得到错误。可以看到图片中的错误:ibb.co/qRt9M62
    • 对不起,我的错。您应该将要测试的函数名称提供给 spyOn 方法(“removeItem”)。我已经相应地更新了脚本。你现在可以检查吗?
    猜你喜欢
    • 2021-01-01
    • 1970-01-01
    • 2021-04-19
    • 2019-04-09
    • 1970-01-01
    • 2021-03-17
    • 2018-08-27
    • 2020-02-15
    • 1970-01-01
    相关资源
    最近更新 更多