Использовать unmountComponentAtNode или document.body.removeChild при завершении теста? - PullRequest
5 голосов
/ 31 октября 2019

Из этого документа: 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?

Обновление

Эти два официальных документа дают эти два способа при завершении теста, означает ли это, что оба они в порядке? Они эквивалентны? Или что?

1 Ответ

0 голосов
/ 31 октября 2019

unmountComponentAtNode вызовет componentWillUnmount метод жизненного цикла, но document.body.removeChild не будет.

...