1

I am using useAsync() hook within my function component. This component is rendered at last step of material-ui stepper after next button is clicked in previous step, which is a separate component.

const memberStatus = useAsync(async () => {
    await addMembersToTeam(props.projectName, props.teamName, props.members);
  }, []);

Below is the snippet of my test:

const promise = new Promise<any>((_resolve, reject) => {
      reject(new Error('failed'))
    })
    mocked(mockAddMembersToTeam).mockRejectedValue(promise)

    const nextButton = await rendered.findByRole('button', { name: /next/ });
    expect(nextButton).toBeEnabled();
    userEvent.click(nextButton);

await waitFor(() => { expect(mockAddMembersToTeam).toHaveBeenCalledOnce() })

const errorAlert = await waitFor(() =>
      rendered.getByTestId('membersStatusErrorMsg'),
    );

    const expectedAlert = 'Issue Adding Members.';
    expect(errorAlert.textContent).toBe(expectedAlert);

Test is failing with below:

ReferenceError: You are trying to access a property or method of the Jest environment after it has been torn down.

 failed
      281 |     const promise = new Promise<any>((_resolve, reject) => {
    > 282 |       reject(new Error('failed'))
          |              ^
      283 |     })

I appreciate any insights in to this issue. Thanks.

Alwaysalearner
  • 85
  • 1
  • 1
  • 10

1 Answers1

0

I was having similar issue,

First, you don't need to return a rejected promise when calling mockRejectedValue. you can return the error directly from there. It'll wrap in a promise for you.

it("returns any rejected error", async () => {
    const fetcher = jest.fn();
    const error = new Error("dfdf");
    error.response = { bar: "foo" };
    fetcher.mockRejectedValue(error);
    const { result } = renderHook(() => useGet(fetcher));
    await waitFor(() => {
      expect(result.current.response).toStrictEqual({ bar: "foo" });
    });
  });

or

it("returns any rejected error", async () => {
    const fetcher = jest.fn();
    fetcher.mockRejectedValue({ response: { bar: "foo" } });
    const { result } = renderHook(() => useGet(fetcher));
    await waitFor(() => {
      expect(result.current.response).toStrictEqual({ bar: "foo" });
    });
  });

since for me I only care about the response attribute of the error

Manoel Quirino Neto
  • 1,261
  • 1
  • 9
  • 2