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?
.
Why is jest surprised by the logging done in the promise continuation in the second test but not the second test?
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();
});
});