Search code examples
reactjsreact-hooksasync-awaitjestjsreact-testing-library

React testing error Cannot log after tests are done. Did you forget to wait for something async in your test?


I have a functional component which I am trying to test and there seems to be some issue around the endpoint call via axios.

const url = user.myUrl + "/someEndpoint";
const RESPONSE = await axios.post(url);
console.log("RESPONSE ::::::::::::::::::::::::" + RESPONSE);

The test is as below;

test("Validate something", async () => {
    const {container} = render(
            <MyComponent url={url} />
    );
    expect(await container.getElementsByClassName('someGrid').length).toBe(2);
});

When I run the test, I get the below error;

Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log "RESPONSE ::::::::::::::::::::::::[object Object]".      

PS: I am mocking endpoints via msw.


Solution

  • As MyComponent has an effect in it i.e. an axios POST, you need to wait for the result. Hence try changing your test to:

    test("Validate something", async () => {
        const {container} = render(<MyComponent url={url} />);
        await waitFor(() => expect(container.getElementsByClassName('someGrid').length).toBe(2));
    });
    

    (You'll most likely need to import waitFor if you don't already use it)