Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest + React-testing-library - wait for a mocked async function to complete

My componentDidMount() fires off a call to an async function but depending on the result of that function, it might not result in any DOM change. Is there any way I can wait for the function to complete in my tests?

Here's an example - the click button is initially disabled. If the async function returns true, the click button should be enabled:

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

But if it returns false the button stays disabled:

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

The second test does actually work but the empty waitFor() is considsered bad practice. is there any way to avoid this?

like image 788
Andy Avatar asked Dec 31 '22 05:12

Andy


1 Answers

In the docs for waitFor, it is recommended to just wait for your async function .toHaveBeenCalled like so

await waitFor(() => expect(mockAPI).toHaveBeenCalledTimes(1))
like image 56
Koleok Avatar answered May 07 '23 02:05

Koleok