Skip to content

Commit

Permalink
fix(findComponent): return root instance if it matches (#834)
Browse files Browse the repository at this point in the history
  • Loading branch information
xanf authored Aug 12, 2021
1 parent 01db5a9 commit 20f08d4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
10 changes: 5 additions & 5 deletions src/vueWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,11 +160,6 @@ export class VueWrapper<T extends ComponentPublicInstance>
}
}

const result = find(this.vm.$.subTree, selector)
if (result.length) {
return createWrapper(null, result[0])
}

// https://github.com/vuejs/vue-test-utils-next/issues/211
// VTU v1 supported finding the component mounted itself.
// eg: mount(Comp).findComponent(Comp)
Expand All @@ -173,6 +168,11 @@ export class VueWrapper<T extends ComponentPublicInstance>
return createWrapper(null, this.vm.$.vnode.component?.proxy!)
}

const result = find(this.vm.$.subTree, selector)
if (result.length) {
return createWrapper(null, result[0])
}

return createWrapperError('VueWrapper')
}

Expand Down
22 changes: 13 additions & 9 deletions tests/findComponent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,6 @@ describe('findComponent', () => {
)
})

it('finds a component when root of mounted component', async () => {
const wrapper = mount(compD)
// make sure it finds the component, not its root
expect(wrapper.findComponent('.c-as-root-on-d').vm).toHaveProperty(
'$options.name',
'ComponentC'
)
})

it('finds component by name', () => {
const wrapper = mount(compA)
expect(wrapper.findComponent({ name: 'Hello' }).text()).toBe('Hello world')
Expand All @@ -109,6 +100,19 @@ describe('findComponent', () => {
expect(wrapper.html()).toContain('bar')
})

it('finds root component when recursion is used', async () => {
const Comp = defineComponent({
props: ['depth'],
name: 'Comp',
template: `
<Comp :depth="depth + 1" v-if="depth < 2" />
Depth {{ depth }}
`
})
const wrapper = mount(Comp, { props: { depth: 0 } })
expect(wrapper.findComponent(Comp).props('depth')).toBe(0)
})

it('finds component without a name by using its object definition', () => {
const Component = {
template: '<div><component-without-name/></div>',
Expand Down

0 comments on commit 20f08d4

Please sign in to comment.