Jest mocked alert not being called when tested with unit tests

15 views Asked by At

I have this issue when trying to test a an alert being thrown in a catch method of a promise.

This is what it looks like:

      update()
        .then((response) => {
          ...
        })
        .catch((reason) => {
        
          alert(
            "Error when updating. Reason: " + (reason as Error).message
          );
        });

then in unit test I am trying to verify that the alert was called (the alert is spied in the test)

 test("error ", async () => {
    //other mocks for data retrieve
    (useLoaderData as jest.Mock).mockImplementation(
      () => someData
    );
    jest.spyOn(moduleClients, "getClient").mockResolvedValue(
      Promise.resolve({
        send: jest.fn(() => {
          throw new Error();
        }), // throwing an error will result in failure to submit the form
      } as unknown as FaaConfigurationClient)
    );

    //window alert mock
    jest.spyOn(window, "alert").mockImplementation(() => {
    });

    const { container, getByText } = render(<SomeView />);

    const elementWrapper = createWrapper(container);

    let formElement = elementWrapper.findForm().getElement();
    formElement.onsubmit = jest.fn();
    await act(async () => {
      fireEvent.submit(formElement);
      expect(formElement.onsubmit).toHaveBeenCalled();

      //THIS FAILS - i expect window.alert to have been called
      expect(window.alert).toHaveBeenCalled();
    });
  });

Does anybody have an idea what is the reason for the failed call for window.alert?

0

There are 0 answers