【问题标题】:Test is passing, but assertion error given after测试通过,但之后给出断言错误
【发布时间】:2020-03-12 15:29:55
【问题描述】:

我有这种奇怪的情况,我不明白。

在我的 vue 组件中,我使用“存储库/服务”进行 API 调用。它使用 axios:

我在一个组件中导入它:

import { RepositoryFactory } from "AMComponents/repositories/repository-factory";
const ContactsRepository = RepositoryFactory.get("contacts");

addContact 方法中,我是这样使用它的:

现在, 我是这样测试的:

    test("addContact", () => {
      const newContact = {
        "name": "Hulk Hogan",
        "email": "hulk@hogan.com",
        "phone": "",
        "additional_information": "Hulkamania is running wild, Brother",
        "type": "advertiser",
      };
      ContactsRepository.createContact = jest.fn()
        .mockResolvedValue({
          data: {
            response: {
              contact_information: [...contacts, newContact],
              passport_privileges: {},
            },
          },
        })
        .mockRejectedValue({
          response: {
            status: 400,
            data: {
              messages: ["mocked error"],
            },
          },
        });

      window.toastr = {
        success: jest.fn(),
        error: jest.fn(),
      };
      wrapper.vm.addContact(newContact);

      expect(wrapper.vm.saving).toBe(true);
      expect(ContactsRepository.createContact).toHaveBeenCalled();

      flushPromises()
        .then(() => {
          expect(1).toBe(2); // <-- here is where I expect my test to fail
          expect(wrapper.vm.saving).toBe(false);
          expect(window.toastr.error).toHaveBeenCalled();
          expect(wrapper.emitted("update")[0][0]).toEqual([...contacts, newContact]);
        })
        .catch((error) => {
          throw Error(error)
        })
    });

我预计我的测试会失败,因为我使用了断言expect(1).toBe(2)。 相反,我有这样的结果:

我花了大约 5 小时尝试不同的解决方案来完成这项工作,但没有运气。

你能解释一下这里发生了什么吗?或者至少为我指明正确的方向。

【问题讨论】:

    标签: unit-testing vue.js testing jestjs vue-test-utils


    【解决方案1】:

    又过了一天,我能够提供解决问题的方法。

    我已经修改了jest-setup.js 以便能够使用async await

    -  test("addContact", () => {
    +  test("addContact", async () => {
    
    ... //  no changes
    
    -    flushPromises()
    -     .then(() => {
    
    +    await flushPromises();
    
         expect(1).toBe(2); // <-- now test fail here as expected ;-)
    
         expect(wrapper.vm.saving).toBe(false);
         expect(window.toastr.error).toHaveBeenCalled();
         expect(wrapper.emitted("update")[0][0]).toEqual([...contacts, newContact]);
       })
    -     .catch((error) => {
    -       throw Error(error)
    -     })
    
       });
    
    

    虽然现在可以正常工作,但我仍然不知道为什么 Promise 不起作用。所以仍然欢迎任何建议:)

    【讨论】:

      猜你喜欢
      • 2017-04-01
      • 2018-09-07
      • 2019-04-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 2011-03-25
      相关资源
      最近更新 更多