Skip to content

Commit

Permalink
fix: findComponent with ref inside v-for (vuejs#1443)
Browse files Browse the repository at this point in the history
  • Loading branch information
freakzlike authored Apr 20, 2022
1 parent 7b8d0a3 commit f027ce3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/baseWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,13 @@ export default abstract class BaseWrapper<ElementType extends Node>
}

if (typeof selector === 'object' && 'ref' in selector) {
const result = currentComponent.refs[selector.ref]
let result = currentComponent.refs[selector.ref]

// When using ref inside v-for, then refs contains array of component instances
if (Array.isArray(result)) {
result = result.length ? result[0] : undefined
}

if (result && !(result instanceof HTMLElement)) {
return createVueWrapper(null, result as ComponentPublicInstance)
} else {
Expand Down
23 changes: 23 additions & 0 deletions tests/findComponent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,29 @@ describe('findComponent', () => {
expect(compB[0].vm.$el.querySelector('.content').textContent).toBe('1')
})

it('finds single by ref in v-for', () => {
const ChildComp = {
props: {
value: Number
},
template: '<span>{{value}}</span>'
}

const wrapper = mount({
components: { ChildComp },
template: `
<div>
<div v-for="value in 3" :key="value">
<ChildComp ref="child" :value="value" />
</div>
</div>
`
})
const child = wrapper.findComponent({ ref: 'child' })
expect(child.exists()).toBe(true)
expect(child.props('value')).toBe(1)
})

// https://github.com/vuejs/test-utils/pull/188
const slotComponent = defineComponent({
name: 'slotA',
Expand Down

0 comments on commit f027ce3

Please sign in to comment.