测试通过,但是之后给出断言错误

我有这种奇怪的情况,我不理解。

在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个小时尝试不同的解决方案来使这项工作顺利进行。

您能告诉我这是怎么回事吗?或者至少将我指向正确的方向。

kubabel 回答:测试通过,但是之后给出断言错误

花了一天的时间后,我可以为我的问题提供解决方案。

我已修改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不能正常工作。因此,仍然欢迎任何建议:)

本文链接:https://www.f2er.com/3088779.html

大家都在问