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?