I´m encountering a peculiar situation. I´m running jest tests for react and it passes as successful, but returns me this warning:
console.error
Warning: An update to App 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 */
Here´s a short snippet of some of the rendered error code that´s pointing to:
const handleFirstNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFirstNumber(
^
e.target.value !== '' ? Number(e.target.value.replace(/\D*/g, '')) : null
);
};
My setup:
- node: 16.14.2
- npm: 8.5.5
- jest": 29.3.1
- react-test-renderer: 18.2.0
- react: 18.2.0
- react-dom: 18.2.0
- react-scripts: 5.0.1
- @testing-library/jest-dom: 5.16.5
- @testing-library/react: 13.4.0
- @testing-library/user-event": 14.4.3
My testing code:
import React from 'react';
import { act } from 'react-dom/test-utils';
import { render, screen, RenderResult, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import App from '../pathToDirectory/App';
describe('My tests', () => {
it('Should display xx', async () => {
render(<App />);
await userEvent.type(screen.getByLabelText('Number A'), '123');
await userEvent.type(screen.getByLabelText('Number B'), '321');
await userEvent.click(screen.getByRole('button'));
await waitFor(() => {
expect(screen.getByText('xx')).toBeInTheDocument();
});
});
});
So far, I´ve consulted these sources:
- When testing, code that causes React state updates should be wrapped into act
- How to solve the "update was not wrapped in act()" warning in testing-library-react?
- https://legacy.reactjs.org/docs/test-utils.html#act
- https://davidwcai.medium.com/react-testing-library-and-the-not-wrapped-in-act-errors-491a5629193b
- https://kentcdodds.com/blog/fix-the-not-wrapped-in-act-warning
- https://dev.to/il3ven/fix-warning-in-react-update-was-not-wrapped-in-act-bk6
None of the proposed solutions resolved my problem. Anyone else have any suggestions so I won't receive these warnings?