0

I have this weird situation which I don't understand.

In my vue component I use "Repository / Service" for making API calls. It uses axios: enter image description here

I import it in a component:

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

And in method addContact I use it like that: enter image description here

Now, This is how I test it:

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

What I exppect my test to fail because I use assertion expect(1).toBe(2). Instead I have a result like that: enter image description here

I have spend like 5h trying different solutions to make this work, with no luck.

Can you explain to me what is going on here? Or at least point me to right direction.

Adam Orłowski
  • 4,268
  • 24
  • 33

1 Answers1

0

After spending another day I am able to suplie solution to my problem.

I have modified jest-setup.js to be able to use 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)
-     })

   });

Anthough this works correctly now, I still don't know why Promise didin't work. So any suggestions are still welcome :)

Adam Orłowski
  • 4,268
  • 24
  • 33