reactjs / reactjs/react.dev

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

未关闭
#4,911 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
11

描述

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.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

https://reactjs.org/docs/testing-recipes.html 上的“Testing Recipes”页面开始,将其中的 cleanup 和 rendering 示例与 issue 中链接的“React 18 upgrade guide”进行比较。检查建议的 createRoot、root.unmount() 和 act() 用法,然后更新 recipes,使其反映 React 18 testing API,并且不再展示过时的模式。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
基本清楚
新手友好度
38/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。