-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Closed
Description
@testing-library/react
version: 12.1.2 (but even found in v11)- Testing Framework and version: jest 27 (but even found in v26)
- DOM Environment: 16.7.0
Relevant code or config:
import React, {useEffect, useRef, useState} from 'react';
import {render} from '@testing-library/react';
const MyComponent = () => {
const [, setValue] = useState(0);
const mountedRef = useRef(true);
useEffect(() => {
Promise.resolve().then(() => {
if (mountedRef.current) {
setValue(1);
}
});
return () => {
mountedRef.current = false;
};
}, []);
return null;
};
describe('bug', () => {
it('should not update state after unmounted', () => {
render(<MyComponent />);
});
});
What you did:
Run the test and see the console warning.
What happened:
console.error
Warning: An update to MyComponent inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
Problem description:
The test run, but a warning is printed in the console. If we use the unmount
inside the it
, then there is no such warning.
Running the unmount
inside the test should not be needed as it runs in the afterEach => cleanup => unmount
(see api doc).
See the cleanup
is added to afterEach
on jest and triggered, but seems "later" that if call it inside the same test.
react-testing-library/src/index.js
Line 13 in 8f17a2b
cleanup() |
no warning:
it('should not update state after unmounted', () => {
render(<MyComponent />);
cleanup();
});
emileber, tychenjiajun and SethDavenport
Metadata
Metadata
Assignees
Labels
No labels