Skip to content

Commit 0ef42ee

Browse files
committed
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 vuejs#1578 for details and discussion
1 parent bb949a1 commit 0ef42ee

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Diff for: docs/api/options.md

+4
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,10 @@ HTMLElement, to which your component will be fully mounted in the document.
302302
When attaching to the DOM, you should call `wrapper.destroy()` at the end of your test to
303303
remove the rendered elements from the document and destroy the component instance.
304304

305+
::: tip
306+
When using `attachTo: document.body` new `div` instead of replacing entire body new `<div>` 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
307+
:::
308+
305309
```js
306310
const div = document.createElement('div')
307311
div.id = 'root'

Diff for: packages/test-utils/src/mount.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@ export default function mount(component, options = {}) {
3232
const parentVm = createInstance(component, mergedOptions, _Vue)
3333

3434
const el =
35-
options.attachTo || (options.attachToDocument ? createElement() : undefined)
35+
options.attachToDocument || options.attachTo instanceof HTMLBodyElement
36+
? createElement()
37+
: options.attachTo
3638
const vm = parentVm.$mount(el)
3739

3840
component._Ctor = {}

Diff for: test/specs/mounting-options/attachTo.spec.js

+14
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,20 @@ describeWithShallowAndMount('options.attachTo', mountingMethod => {
3232
wrapper.destroy()
3333
expect(document.getElementById('attach-to')).toBeNull()
3434
})
35+
it('appends new node when attached to document.body', () => {
36+
const unrelatedDiv = document.createElement('div')
37+
unrelatedDiv.id = 'unrelated'
38+
document.body.appendChild(unrelatedDiv)
39+
const wrapper = mountingMethod(TestComponent, {
40+
attachTo: document.body
41+
})
42+
expect(document.body.contains(unrelatedDiv)).toBe(true)
43+
expect(wrapper.vm.$el.parentNode).toBe(document.body)
44+
expect(wrapper.options.attachedToDocument).toEqual(true)
45+
wrapper.destroy()
46+
unrelatedDiv.remove()
47+
expect(document.body.children).toHaveLength(0)
48+
})
3549
it('attaches to a provided CSS selector string', () => {
3650
const div = document.createElement('div')
3751
div.id = 'root'

0 commit comments

Comments
 (0)