Skip to content

Commit cb6f29d

Browse files
cexbrayatlmiller1990
authored andcommitted
fix: return empty string for text() on comments
Fixes vuejs#342
1 parent a60fcb1 commit cb6f29d

File tree

4 files changed

+25
-3
lines changed

4 files changed

+25
-3
lines changed

src/domWrapper.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { createWrapperError } from './errorWrapper'
44
import { TriggerOptions, createDOMEvent } from './createDomEvent'
55
import { config } from './config'
66
import { isElementVisible } from './utils/isElementVisible'
7+
import { textContent } from './utils'
78

89
export class DOMWrapper<ElementType extends Element> {
910
element: ElementType
@@ -45,7 +46,7 @@ export class DOMWrapper<ElementType extends Element> {
4546
}
4647

4748
text() {
48-
return this.element.textContent?.trim()
49+
return textContent(this.element)
4950
}
5051

5152
html() {

src/utils.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,11 @@ export function isHTML(str: string) {
9696

9797
return false
9898
}
99+
100+
export function textContent(element: Element): string {
101+
// we check if the element is a comment first
102+
// to return an empty string in that case, instead of the comment content
103+
return element.nodeType !== Node.COMMENT_NODE
104+
? element.textContent?.trim()
105+
: ''
106+
}

src/vueWrapper.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { FindAllComponentsSelector, FindComponentSelector } from './types'
77
import { createWrapperError } from './errorWrapper'
88
import { TriggerOptions } from './createDomEvent'
99
import { find, matches } from './utils/find'
10-
import { mergeDeep } from './utils'
10+
import { mergeDeep, textContent } from './utils'
1111
import { emitted } from './emit'
1212

1313
export class VueWrapper<T extends ComponentPublicInstance> {
@@ -86,7 +86,7 @@ export class VueWrapper<T extends ComponentPublicInstance> {
8686
}
8787

8888
text() {
89-
return this.element.textContent?.trim()
89+
return textContent(this.element)
9090
}
9191

9292
find<K extends keyof HTMLElementTagNameMap>(

tests/text.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,17 @@ describe('text', () => {
2626

2727
expect(wrapper.text()).toBe('foobarbaz')
2828
})
29+
30+
it('returns empty string when the root element is a comment', () => {
31+
const Component = defineComponent({
32+
template: '<div v-if="condition">Hello</div>',
33+
setup() {
34+
return { condition: false }
35+
}
36+
})
37+
38+
const wrapper = mount(Component)
39+
40+
expect(wrapper.text()).toBe('')
41+
})
2942
})

0 commit comments

Comments
 (0)