Skip to content

Commit

Permalink
fix: Gracefully handle empty root node for nested component (#660)
Browse files Browse the repository at this point in the history
* fix: handle find(All) on components with comment root node in edge case
Squashed commits:
[00c8592] fix: apply same fix for findAll
[acbc848] fix: handle find() when root node is placeholder comment

* chore: formatting

* chore: fix typecasting
  • Loading branch information
LinusBorg authored Jun 12, 2021
1 parent 70b13f0 commit d64698c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/vueWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export class VueWrapper<T extends ComponentPublicInstance>
const result = this.parentElement['__vue_app__']
? // force using the parentElement to allow finding the root element
this.parentElement.querySelector(selector)
: this.element.querySelector(selector)
: this.element.querySelector && this.element.querySelector(selector)

if (result) {
return new DOMWrapper(result)
Expand Down Expand Up @@ -223,7 +223,9 @@ export class VueWrapper<T extends ComponentPublicInstance>
findAll(selector: string): DOMWrapper<Element>[] {
const results = this.parentElement['__vue_app__']
? this.parentElement.querySelectorAll(selector)
: this.element.querySelectorAll(selector)
: this.element.querySelectorAll
? this.element.querySelectorAll(selector)
: ([] as unknown as NodeListOf<Element>)

return Array.from(results).map((element) => new DOMWrapper(element))
}
Expand Down
32 changes: 32 additions & 0 deletions tests/find.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,22 @@ describe('find', () => {
)
expect(foundElement.exists()).toBeFalsy()
})

test('handle empty root node', () => {
const EmptyTestComponent = {
name: 'EmptyTestComponent',
render: () => null
}
const Component = defineComponent({
render() {
return h('div', [h(EmptyTestComponent)])
}
})

const wrapper = mount(Component)
const etc = wrapper.findComponent({ name: 'EmptyTestComponent' })
expect(etc.find('p').exists()).toBe(false)
})
})

describe('findAll', () => {
Expand Down Expand Up @@ -178,4 +194,20 @@ describe('findAll', () => {

expect(wrapper.find('#foo').find('#bar').exists()).toBe(true)
})

test('handle empty/comment root node', () => {
const EmptyTestComponent = {
name: 'EmptyTestComponent',
render: () => null
}
const Component = defineComponent({
render() {
return h('div', [h(EmptyTestComponent)])
}
})

const wrapper = mount(Component)
const etc = wrapper.findComponent({ name: 'EmptyTestComponent' })
expect(etc.findAll('p')).toHaveLength(0)
})
})

0 comments on commit d64698c

Please sign in to comment.