.detach() => void
Отсоединяет дерево react от DOM. Выполняет ReactDOM.unmountComponentAtNode() под капотом.
Этот метод чаще всего используется в качестве метода «очистки», если вы решите использовать опцию attachTo или hydrateIn в mount(node, options).
Метод намеренно не является «потоком» (то есть не возвращает this), так как после вызова этого метода вы не должны ничего делать с этим обёрткой.
Использование attachTo/hydrateIn обычно не рекомендуется, если это не абсолютно необходимо для тестирования. Вы несёте ответственность за очистку после себя в конце теста, если всё-таки решите его использовать.
Примеры
С помощью опции attachTo, вы можете монтировать компоненты на присоединённые элементы DOM:
// render a component directly into document.body
const wrapper = mount(<Bar />, { attachTo: document.body });
// Or, with the `hydrateIn` option, you can mount components on top of existing DOM elements:
// hydrate a component directly onto document.body
const hydratedWrapper = mount(<Bar />, { hydrateIn: document.body });
// we can see that the component is rendered into the document
expect(wrapper.find('.in-bar')).to.have.lengthOf(1);
expect(document.body.childNodes).to.have.lengthOf(1);
// detach it to clean up after yourself
wrapper.detach();
// now we can see that
expect(document.body.childNodes).to.have.lengthOf(0);
Аналогично, если вы хотите создать некоторые разовые элементы для вашего теста, чтобы смонтировать их в:
// create a div in the document to mount into
const div = global.document.createElement('div');
global.document.body.appendChild(div);
// div is empty. body has the div attached.
expect(document.body.childNodes).to.have.lengthOf(1);
expect(div.childNodes).to.have.lengthOf(0);
// mount a component passing div into the `attachTo` option
const wrapper = mount(<Foo />, { attachTo: div });
// or, mount a component passing div into the `hydrateIn` option
const hydratedWrapper = mount(<Foo />, { hydrateIn: div });
// we can see now the component is rendered into the document
expect(wrapper.find('.in-foo')).to.have.lengthOf(1);
expect(document.body.childNodes).to.have.lengthOf(1);
expect(div.childNodes).to.have.lengthOf(1);
// call detach to clean up
wrapper.detach();
// div is now empty, but still attached to the document
expect(document.body.childNodes).to.have.lengthOf(1);
expect(div.childNodes).to.have.lengthOf(0);
// remove div if you want
global.document.body.removeChild(div);
expect(document.body.childNodes).to.have.lengthOf(0);
expect(div.childNodes).to.have.lengthOf(0);
© 2015 Airbnb, Inc.
Licensed under the MIT License.
https://enzymejs.github.io/enzyme/docs/api/ReactWrapper/detach.html