1

I have the following simple test file for the component. I based the test on this React documentation https://reactjs.org/docs/test-utils.html#act

import ReactDOM from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import App from './App'
import { screen } from '@testing-library/react'

let container: HTMLElement;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
});

it('can render and update a counter', () => {
  act(() => {
    ReactDOM.createRoot(container).render(<App />);
  });
  const title = screen.getByText('My App');
  expect(title).toBeInTheDocument()
});

The test does pass, but I always receive an annoying error:

  Warning: A suspended resource finished loading inside a test, but the event was not wrapped in act(...).
  
  When testing, code that resolves suspended data should be wrapped into act(...):
  
  act(() => {
    /* finish loading suspended data */
  });
  /* 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

When I remove from the a component which uses react lazy loading the error message goes away. So how can I test over React Lazy Loading without this kind of issue for React 18?

Here is my setupTest.ts

import '@testing-library/jest-dom';

Here is my package.json dependencies

"dependencies": {
    "@react-spring/web": "^9.4.5",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "styled-components": "^5.3.5"
 },
"devDependencies": {
    "@react-spring/types": "^9.4.5",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.1",
    "@types/react": "^18.0.9",
    "@types/react-dom": "^18.0.5",
    "@types/styled-components": "^5.1.25",
    "@typescript-eslint/eslint-plugin": "^5.36.1",
    "@typescript-eslint/parser": "^5.36.1",
    "eslint": "^8.23.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-import-resolver-typescript": "^3.5.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-prettier": "^4.2.1",
    "eslint-plugin-react": "^7.31.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "prettier": "^2.7.1",
    "react-scripts": "5.0.1",
    "typescript": "^4.6.4"
  }

I already tried several solutions like using await waitFor(...), findBy(...), removing the act method from the test file, but no success yet.

I'm using Node 16.16

2 Answers2

1

I just resolved it by inserting this lines at the end of the test:

await screen.findByText('some text');

I understood that since changes occurs after the initial render, we need to "tell" the Testing Library that it does and to wait for it. It does not need the act() wrapping the render method then.

-1

did you try putting your

const title = screen.getByText('My App');

line of code inside act(){...}?

Swain
  • 52
  • 3