Skip to content

Commit f027ce3

Browse files
authored
fix: findComponent with ref inside v-for (#1443)
1 parent 7b8d0a3 commit f027ce3

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/baseWrapper.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,13 @@ export default abstract class BaseWrapper<ElementType extends Node>
125125
}
126126

127127
if (typeof selector === 'object' && 'ref' in selector) {
128-
const result = currentComponent.refs[selector.ref]
128+
let result = currentComponent.refs[selector.ref]
129+
130+
// When using ref inside v-for, then refs contains array of component instances
131+
if (Array.isArray(result)) {
132+
result = result.length ? result[0] : undefined
133+
}
134+
129135
if (result && !(result instanceof HTMLElement)) {
130136
return createVueWrapper(null, result as ComponentPublicInstance)
131137
} else {

tests/findComponent.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,29 @@ describe('findComponent', () => {
358358
expect(compB[0].vm.$el.querySelector('.content').textContent).toBe('1')
359359
})
360360

361+
it('finds single by ref in v-for', () => {
362+
const ChildComp = {
363+
props: {
364+
value: Number
365+
},
366+
template: '<span>{{value}}</span>'
367+
}
368+
369+
const wrapper = mount({
370+
components: { ChildComp },
371+
template: `
372+
<div>
373+
<div v-for="value in 3" :key="value">
374+
<ChildComp ref="child" :value="value" />
375+
</div>
376+
</div>
377+
`
378+
})
379+
const child = wrapper.findComponent({ ref: 'child' })
380+
expect(child.exists()).toBe(true)
381+
expect(child.props('value')).toBe(1)
382+
})
383+
361384
// https://github.com/vuejs/test-utils/pull/188
362385
const slotComponent = defineComponent({
363386
name: 'slotA',

0 commit comments

Comments
 (0)