Jest + React-testing-library-等待模拟的异步功能完成

问题描述 投票:0回答:1

我的componentDidMount()触发了对异步函数的调用,但是取决于该函数的结果,它可能不会导致任何DOM更改。有什么方法可以等待我的功能在测试中完成?

这里是一个示例-最初禁用了单击按钮。如果异步函数返回true,则应启用单击按钮:

    myAsyncFunction.mockImplementation(() => true);
    const {queryByText} = render(<Component />);
    const button = queryByText("Click");
    expect(button).toBeDisabled();
    await waitFor( () => expect(button).not.toBeDisabled() );
    expect(button).not.toBeDisabled();

但是如果返回false,则按钮保持禁用状态:

    myAsyncFunction.mockImplementation(() => false);   // async returning different value
    const {queryByText} = render(<Component />);
    const button = queryByText("Click");
    expect(button).toBeDisabled();
    await waitFor( () => {} );                       //        <== **** CODE SMELL ****
    expect(button).toBeDisabled();

第二项测试确实有效,但是空的waitFor()被认为是不良做法。有什么办法可以避免这种情况?

jestjs react-testing-library
1个回答
1
投票

waitFor的文档中,建议像这样等待异步函数.toHaveBeenCalled

await waitFor(() => expect(mockAPI).toHaveBeenCalledTimes(1))
© www.soinside.com 2019 - 2024. All rights reserved.