react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

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

Open yosipy opened this issue 3 years ago • 0 comments
trafficstars

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.

yosipy avatar Aug 18 '22 06:08 yosipy