0

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:

None of the proposed solutions resolved my problem. Anyone else have any suggestions so I won't receive these warnings?

Jorge Mauricio
  • 411
  • 6
  • 18

1 Answers1

0

After tons of research, found a fix for it in this post: https://github.com/testing-library/react-testing-library/issues/1051

For some reason, userEvent was causing the warnings, so I had to change to fireEvent and the warnings stopped. Here's how the code was changed:

import React from 'react';
import { render, screen, fireEvent} from '@testing-library/react';
import App from '../pathToDirectory/App';

describe('My tests', () => {
  it('Should display xx', async () => {
    render(<App />);

    fireEvent.change(screen.getByLabelText('Number A'), {
        target: { value: 123 },
    });
    fireEvent.change(screen.getByLabelText('Number B'), {
        target: { value: 321 },
    });
    fireEvent.click(screen.getByRole('button'));
    
    expect(screen.getByText('xx')).toBeInTheDocument();
  });
});
Jorge Mauricio
  • 411
  • 6
  • 18