javascript - 拆卸测试时使用 unmountComponentAtNode 或 document.body.removeChild ?

标签 javascript reactjs react-dom react-test-renderer

从此文档:https://reactjs.org/docs/hooks-faq.html#how-to-test-components-that-use-hooks

文档提供了一种设置和拆卸测试的方法,如下所示:

let container;

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

afterEach(() => {
  document.body.removeChild(container);
  container = null;
});

从此文档:https://reactjs.org/docs/testing-recipes.html#setup--teardown

安装和拆卸方式如下:

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;
});

我有点困惑哪一种是拆解测试的最佳方法?

unmountComponentAtNode + dom.remove() 还是 document.body.removeChild

更新

这两个官方文档在teardown测试的时候给出了这两种方式,是不是说明这两种方式都可以呢?它们相等吗?或者,什么?

最佳答案

unmountComponentAtNode 将调用 componentWillUnmount 生命周期方法,但 document.body.removeChild 不会。

关于javascript - 拆卸测试时使用 unmountComponentAtNode 或 document.body.removeChild ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58637602/

相关文章:

javascript - 动态更新对象中的 Getter 函数

reactjs - 如何在 webpack 配置文件中启用 babel stage-0

javascript - 如何找到焦点React组件? (如 document.activeElement)

reactjs - react 测试库渲染 VS ReactDOM.render

c# - 如何从 javascript 填充文本框值并执行剩余代码

javascript - 按钮值没有改变

javascript - 通过链接 jQuery 将函数作为参数传递

javascript - 没有数据时如何重新设计表格

javascript - Redux action 支持意外行为

javascript - 如何使用 React 从 json 对象创建列表