Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(wrapper): allow destroy() method to work with functional components #1188

Merged
merged 11 commits into from Mar 22, 2019
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