Skip to content

Commit

Permalink
feat: treat document.body in attachTo in special way (#1699)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
xanf committed Oct 1, 2020
1 parent 7740e90 commit a821908
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs/api/options.md
Expand Up @@ -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 `<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
:::

```js
const div = document.createElement('div')
div.id = 'root'
Expand Down
4 changes: 3 additions & 1 deletion packages/test-utils/src/mount.js
Expand Up @@ -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 = {}
Expand Down
13 changes: 13 additions & 0 deletions test/specs/mounting-options/attachTo.spec.js
Expand Up @@ -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'
Expand Down

0 comments on commit a821908

Please sign in to comment.