Skip to content

In Testing Recipes, I want to change to use root.unmount() and createRoot. #4911

Description

@yosipy

unmountComponentAtNode is used on Testing Recipes.
https://reactjs.org/docs/testing-recipes.html

However, unmountComponentAtNode(container) has been changed to root.unmount() in react 18.
It also shows to use createRoot.
https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html

So I replaced it in my code as follows

// before

import { unmountComponentAtNode } from "react-dom";

let container = null;
beforeEach(() => {
  // setup a DOM element as a render target
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  // cleanup on exiting
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

// after

import { createRoot } from 'react-dom/client';

let container = null;
let root = null;
beforeEach(() => {
  // setup a DOM element as a render target
  container = document.createElement("div");
  document.body.appendChild(container);
  root = createRoot(container);
});

afterEach(() => {
  // cleanup on exiting
  act(() => root.unmount());
  container.remove();
  container = null;
});

root.unmount() is wrapped in act(...) because it gives the following warning:

    Warning: An update to Root 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

Is this policy and implementation of mine correct?
If correct I will try to create a pull request.

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