Skip to content

Document "How to test React.lazy" #1255

Closed
@atshakil

Description

@atshakil
  • @testing-library/react version: 14.0.0
  • Testing Framework and version: jest
  • DOM Environment:

Relevant code or config:

// Example.tsx

const Example = () => null;
export default Example;

// Example.test.tsx

import { lazy } from "react";
import { render } from "@testing-library/react";

const Component = () => {
  const Example = lazy(() => import("./Example"));

  return <Example />;
};

describe("Example", () => {
  test(`Renders`, () => {
    expect(() => {
      render(<Component />);
    }).not.toThrow();
  });
});

What you did:

Run test using yarn test from a CRA configured project.

What happened:

Receiving warning,

console.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

Reproduction:

Sandbox: https://codesandbox.io/p/sandbox/demo-act-warning-nq3v9h?file=%2Fsrc%2FExample.test.tsx&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A1%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A1%7D%5D

Problem description:

Warning starts to appear after upgrading to React 18.

Suggested solution:

No warning message

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions