Skip to content

Commit

Permalink
feat(wrapper): allow destroy() method to work with functional compone…
Browse files Browse the repository at this point in the history
…nts (#1188)
  • Loading branch information
tmorehouse authored and eddyerburgh committed Mar 22, 2019
1 parent b5b511e commit f4ea3fd
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 5 deletions.
3 changes: 3 additions & 0 deletions docs/api/options.md
Expand Up @@ -206,6 +206,9 @@ expect(wrapper.vm.$route).toBeInstanceOf(Object)

Component will be attached to DOM when rendered if set to `true`.

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.

## attrs

- type: `Object`
Expand Down
5 changes: 5 additions & 0 deletions docs/api/wrapper/destroy.md
Expand Up @@ -17,3 +17,8 @@ mount({
}).destroy()
expect(spy.calledOnce).toBe(true)
```

if `attachToDocument` was set to `true` when mounted, the component DOM elements will
also be removed from the document.

For functional components, `destroy` only removes the rendered DOM elements from the document.
16 changes: 11 additions & 5 deletions packages/test-utils/src/wrapper.js
Expand Up @@ -124,16 +124,22 @@ export default class Wrapper implements BaseWrapper {
* Calls destroy on vm
*/
destroy(): void {
if (!this.isVueInstance()) {
throwError(`wrapper.destroy() can only be called on a Vue instance`)
if (!this.isVueInstance() && !this.isFunctionalComponent) {
throwError(
`wrapper.destroy() can only be called on a Vue instance or ` +
`functional component.`
)
}

if (this.element.parentNode) {
this.element.parentNode.removeChild(this.element)
}
// $FlowIgnore
this.vm.$destroy()
throwIfInstancesThrew(this.vm)

if (this.isVueInstance()) {
// $FlowIgnore
this.vm.$destroy()
throwIfInstancesThrew(this.vm)
}
}

/**
Expand Down
15 changes: 15 additions & 0 deletions test/specs/wrapper/destroy.spec.js
Expand Up @@ -40,6 +40,21 @@ describeWithShallowAndMount('destroy', mountingMethod => {
expect(wrapper.vm.$el.parentNode).to.be.null
})

it('removes functional component element from document.body', () => {
const wrapper = mountingMethod(
{
functional: true,
render: h => {
return h('div', {}, [])
}
},
{ attachToDocument: true }
)
expect(wrapper.element.parentNode).to.equal(document.body)
wrapper.destroy()
expect(wrapper.element.parentNode).to.be.null
})

it('throws if component throws during destroy', () => {
const TestComponent = {
template: '<div :p="a" />',
Expand Down

0 comments on commit f4ea3fd

Please sign in to comment.