Skip to content

Commit 1e56cc7

Browse files
authored
fix(findComponent): allow finding top-level component (#1496)
* allow finding top-level component when findComponent is chained from dom node rendered by child
1 parent 3c55ab1 commit 1e56cc7

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/domWrapper.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,11 @@ export class DOMWrapper<NodeType extends Node> extends BaseWrapper<NodeType> {
2222
}
2323

2424
getCurrentComponent() {
25-
return this.element.__vueParentComponent
25+
let component = this.element.__vueParentComponent
26+
while (component?.parent?.vnode.el === this.element) {
27+
component = component.parent
28+
}
29+
return component
2630
}
2731

2832
find<K extends keyof HTMLElementTagNameMap>(

tests/findComponent.spec.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,5 +510,34 @@ describe('findComponent', () => {
510510
.classes('inside')
511511
).toBe(true)
512512
})
513+
514+
it('finds top component when searching from nested node', () => {
515+
const DeepNestedComponent = defineComponent({
516+
template: '<div class="deep-nested"></div>'
517+
})
518+
519+
const NestedComponent = defineComponent({
520+
components: { DeepNestedComponent },
521+
template: '<deep-nested-component />'
522+
})
523+
524+
const RootComponent = defineComponent({
525+
components: { NestedComponent },
526+
template: '<nested-component />'
527+
})
528+
529+
const wrapper = mount(RootComponent)
530+
expect(
531+
wrapper.find('.deep-nested').findComponent(DeepNestedComponent).exists()
532+
).toBe(true)
533+
534+
expect(
535+
wrapper.find('.deep-nested').findComponent(NestedComponent).exists()
536+
).toBe(true)
537+
538+
expect(
539+
wrapper.find('.deep-nested').findComponent(RootComponent).exists()
540+
).toBe(true)
541+
})
513542
})
514543
})

0 commit comments

Comments
 (0)