Skip to content

Commit f4ea3fd

Browse files
tmorehouseeddyerburgh
authored andcommittedMar 22, 2019
feat(wrapper): allow destroy() method to work with functional components (#1188)
1 parent b5b511e commit f4ea3fd

File tree

4 files changed

+34
-5
lines changed

4 files changed

+34
-5
lines changed
 

‎docs/api/options.md

+3
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,9 @@ expect(wrapper.vm.$route).toBeInstanceOf(Object)
206206

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

209+
When attaching to the DOM, you should call `wrapper.destroy()` at the end of your test to
210+
remove the rendered elements from the document and destroy the component instance.
211+
209212
## attrs
210213

211214
- type: `Object`

‎docs/api/wrapper/destroy.md

+5
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,8 @@ mount({
1717
}).destroy()
1818
expect(spy.calledOnce).toBe(true)
1919
```
20+
21+
if `attachToDocument` was set to `true` when mounted, the component DOM elements will
22+
also be removed from the document.
23+
24+
For functional components, `destroy` only removes the rendered DOM elements from the document.

‎packages/test-utils/src/wrapper.js

+11-5
Original file line numberDiff line numberDiff line change
@@ -124,16 +124,22 @@ export default class Wrapper implements BaseWrapper {
124124
* Calls destroy on vm
125125
*/
126126
destroy(): void {
127-
if (!this.isVueInstance()) {
128-
throwError(`wrapper.destroy() can only be called on a Vue instance`)
127+
if (!this.isVueInstance() && !this.isFunctionalComponent) {
128+
throwError(
129+
`wrapper.destroy() can only be called on a Vue instance or ` +
130+
`functional component.`
131+
)
129132
}
130133

131134
if (this.element.parentNode) {
132135
this.element.parentNode.removeChild(this.element)
133136
}
134-
// $FlowIgnore
135-
this.vm.$destroy()
136-
throwIfInstancesThrew(this.vm)
137+
138+
if (this.isVueInstance()) {
139+
// $FlowIgnore
140+
this.vm.$destroy()
141+
throwIfInstancesThrew(this.vm)
142+
}
137143
}
138144

139145
/**

‎test/specs/wrapper/destroy.spec.js

+15
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,21 @@ describeWithShallowAndMount('destroy', mountingMethod => {
4040
expect(wrapper.vm.$el.parentNode).to.be.null
4141
})
4242

43+
it('removes functional component element from document.body', () => {
44+
const wrapper = mountingMethod(
45+
{
46+
functional: true,
47+
render: h => {
48+
return h('div', {}, [])
49+
}
50+
},
51+
{ attachToDocument: true }
52+
)
53+
expect(wrapper.element.parentNode).to.equal(document.body)
54+
wrapper.destroy()
55+
expect(wrapper.element.parentNode).to.be.null
56+
})
57+
4358
it('throws if component throws during destroy', () => {
4459
const TestComponent = {
4560
template: '<div :p="a" />',

0 commit comments

Comments
 (0)
Please sign in to comment.