Skip to content

Commit

Permalink
fix: do not crash findComponent if ref is pointing to html element (#817
Browse files Browse the repository at this point in the history
)

* fix: do not crash if ref is pointing to html element

* docs: add warning about findComponent behaviour with ref

* chore: remove extra console.log

Co-authored-by: Adrià Fontcuberta <[email protected]>

Co-authored-by: Adrià Fontcuberta <[email protected]>
  • Loading branch information
xanf and afontcu authored Aug 10, 2021
1 parent fb65416 commit 82a7974
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
4 changes: 4 additions & 0 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1162,6 +1162,10 @@ test('findComponent', () => {
})
```
:::warning
If `ref` in component points to HTML element, `findComponent` will return empty wrapper. This is intended behaviour
:::
**NOTE** `getComponent` and `findComponent` will not work on functional components, because they do not have an internal Vue instance (this is what makes functional components more performant). That means the following will **not** work:
```js
Expand Down
2 changes: 1 addition & 1 deletion src/vueWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export class VueWrapper<T extends ComponentPublicInstance>
): VueWrapper<T> {
if (typeof selector === 'object' && 'ref' in selector) {
const result = this.vm.$refs[selector.ref]
if (result) {
if (result && !(result instanceof HTMLElement)) {
return createWrapper(null, result as T)
} else {
return createWrapperError('VueWrapper')
Expand Down
11 changes: 10 additions & 1 deletion tests/findComponent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,16 @@ describe('findComponent', () => {
it('finds component by ref', () => {
const wrapper = mount(compA)
// find by ref
expect(wrapper.findComponent({ ref: 'hello' })).toBeTruthy()
expect(wrapper.findComponent({ ref: 'hello' }).exists()).toBe(true)
})

it('does not find plain dom element by ref', () => {
const ComponentWithRefOnDomElement = defineComponent({
template: '<div ref="hello">Hello!</div>'
})
const wrapper = mount(ComponentWithRefOnDomElement)

expect(wrapper.findComponent({ ref: 'hello' }).exists()).toBe(false)
})

it('finds component by dom selector', () => {
Expand Down

0 comments on commit 82a7974

Please sign in to comment.