Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jest: Explicit Promises Work Differently From Async Test

It seems like the following tests should have the same result:

import {render, act} from '@testing-library/react';

test('async test', async () => {
    let component;
    await act(()=>{
        component = render(<div/>);
    });
    console.log("logging");
    expect(component).toBeTruthy();
});

test('without callback', () => {
    let component;
    act(()=>{
        component = render(<div/>);
    }).then(()=>{
        console.log("logging");
        expect(component).toBeTruthy();
    });
});

with the following package.json:

{
    "dependencies": {
        "@testing-library/react": "^13.4.0",
        "react-scripts": "5.0.1"
    },
    "scripts": {
        "test": "react-scripts test --verbose",
        "check": "jest --version"
    }
}

The first test succeeds as expected (and I can see its output), but the second test outputs Cannot log after tests are done. Did you forget to wait for something async in your test?.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why is jest surprised by the logging done in the promise continuation in the second test but not the second test?

>Solution :

The second example: there is no way jest to know that it should wait.

If you do not use async/await – you have to return a promise in the test function so that jest knows its a promise and it will wait until the promise is resolved/rejected or timeout has expired.

So code should look like this:

test('without callback', () => {
    let component;
    return act(()=>{
        component = render(<div/>);
    }).then(()=>{
        console.log("logging");
        expect(component).toBeTruthy();
    });
});

https://jestjs.io/docs/asynchronous#promises

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading