笑话测试库 - 模拟拒绝承诺不能按预期在 useAsync() 中工作
Posted
技术标签:
【中文标题】笑话测试库 - 模拟拒绝承诺不能按预期在 useAsync() 中工作【英文标题】:jest testing library - mocking reject promise not working as expected for function within useAsync() 【发布时间】:2021-09-04 03:52:33 【问题描述】:我在我的函数组件中使用 useAsync() 钩子。该组件在上一步点击next按钮后在material-ui stepper的最后一步渲染,是一个单独的组件。
const memberStatus = useAsync(async () =>
await addMembersToTeam(props.projectName, props.teamName, props.members);
, []);
下面是我测试的sn-p:
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 | )
感谢您对此问题的任何见解。谢谢。
【问题讨论】:
【参考方案1】:我也有类似的问题,
首先,调用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" );
);
);
因为我只关心错误的响应属性
【讨论】:
以上是关于笑话测试库 - 模拟拒绝承诺不能按预期在 useAsync() 中工作的主要内容,如果未能解决你的问题,请参考以下文章
除了尝试捕获或承诺拒绝之外,有没有办法处理量角器的预期条件?
从反应原生/[未处理的承诺拒绝:FirebaseError:预期类型'ba',但它是:自定义Oa对象]中获取项目列表