6

From this docs: https://reactjs.org/docs/hooks-faq.html#how-to-test-components-that-use-hooks

The docs provide a way to setup and teardown the test like this:

let container;

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

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

From this docs: https://reactjs.org/docs/testing-recipes.html#setup--teardown

The setup and teardown way like this:

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

I am a little confused which one is the best way to teardown the test?

unmountComponentAtNode + dom.remove() or document.body.removeChild?

Update

These two official docs give these two ways when teardown the test, does it mean both of them are ok? Are they equivalent? Or, what?

Lin Du
  • 88,126
  • 95
  • 281
  • 483

1 Answers1

0

unmountComponentAtNode will invoke componentWillUnmount lifecycle method, but document.body.removeChild will not.

  • 1
    Yeah, I know that. But I think it doesn't answer the question. Both of them are OK or what when teardown the test? – Lin Du Oct 31 '19 at 06:46