0

我在我的函数组件中使用 useAsync() 钩子。该组件在上一步中单击下一步按钮后在 material-ui stepper 的最后一步呈现,这是一个单独的组件。

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

以下是我的测试片段:

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

测试失败,如下:

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

我感谢对此问题的任何见解。谢谢。

4

1 回答 1

0

我有类似的问题,

首先,您不需要在调用时返回被拒绝的承诺mockRejectedValue。您可以直接从那里返回错误。它会给你一个承诺。

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

或者

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

因为对我来说我只关心错误的响应属性

于 2021-12-17T12:20:41.423 回答