From 09a34ddf26c5b2902a8bbdf430bc95a614ac48f1 Mon Sep 17 00:00:00 2001 From: Illya Klymov Date: Mon, 28 Sep 2020 14:03:47 +0300 Subject: [PATCH] feat: treat document.body in attachTo in special way When using attachTo with document.body as a target do not replace original content of body but append a new div instead See #1578 for details and discussion --- docs/api/options.md | 4 ++++ packages/test-utils/src/mount.js | 4 +++- test/specs/mounting-options/attachTo.spec.js | 13 +++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/api/options.md b/docs/api/options.md index fcd76acd7..1bbdd2ae0 100644 --- a/docs/api/options.md +++ b/docs/api/options.md @@ -302,6 +302,10 @@ HTMLElement, to which your component will be fully mounted in the document. When attaching to the DOM, you should call `wrapper.destroy()` at the end of your test to remove the rendered elements from the document and destroy the component instance. +::: tip +When using `attachTo: document.body` new `div` instead of replacing entire body new `
` will be appended. This is designed to mimic Vue3 behavior and simplify future migration. See [this comment](https://github.com/vuejs/vue-test-utils/issues/1578#issuecomment-674652747) for details +::: + ```js const div = document.createElement('div') div.id = 'root' diff --git a/packages/test-utils/src/mount.js b/packages/test-utils/src/mount.js index 4d3b8a6ce..4398e51b8 100644 --- a/packages/test-utils/src/mount.js +++ b/packages/test-utils/src/mount.js @@ -32,7 +32,9 @@ export default function mount(component, options = {}) { const parentVm = createInstance(component, mergedOptions, _Vue) const el = - options.attachTo || (options.attachToDocument ? createElement() : undefined) + options.attachToDocument || options.attachTo instanceof HTMLBodyElement + ? createElement() + : options.attachTo const vm = parentVm.$mount(el) component._Ctor = {} diff --git a/test/specs/mounting-options/attachTo.spec.js b/test/specs/mounting-options/attachTo.spec.js index 65852724c..7df27d7f7 100644 --- a/test/specs/mounting-options/attachTo.spec.js +++ b/test/specs/mounting-options/attachTo.spec.js @@ -32,6 +32,19 @@ describeWithShallowAndMount('options.attachTo', mountingMethod => { wrapper.destroy() expect(document.getElementById('attach-to')).toBeNull() }) + it('appends new node when attached to document.body', () => { + const unrelatedDiv = document.createElement('div') + unrelatedDiv.id = 'unrelated' + document.body.appendChild(unrelatedDiv) + const wrapper = mountingMethod(TestComponent, { + attachTo: document.body + }) + expect(document.body.contains(unrelatedDiv)).toBe(true) + expect(wrapper.vm.$el.parentNode).toBe(document.body) + expect(wrapper.options.attachedToDocument).toEqual(true) + wrapper.destroy() + unrelatedDiv.remove() + }) it('attaches to a provided CSS selector string', () => { const div = document.createElement('div') div.id = 'root'