Skip to content

Commit 3950f8b

Browse files
committed
fix: escape regexp in suggestions
1 parent ceeaaa8 commit 3950f8b

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/__tests__/suggestions.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,16 @@ test('should suggest img role w/ alt text', () => {
163163
)
164164
})
165165

166+
test('escapes regular expressions in suggestion', () => {
167+
renderIntoDocument(
168+
`<img src="foo.png" alt="The Problem (picture of a question mark)" data-testid="foo" />`,
169+
)
170+
171+
expect(() => screen.getByTestId('foo')).toThrowError(
172+
/getByRole\("img", \{name: \/the problem \\\(picture of a question mark\\\)\/i\}\)/,
173+
)
174+
})
175+
166176
test('should suggest getByLabelText when no role available', () => {
167177
renderIntoDocument(
168178
`<label for="foo">Username</label><input data-testid="foo" id="foo" />`,

src/suggestions.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,16 @@ function getLabelTextFor(element) {
2626
}
2727
return undefined
2828
}
29-
29+
function escapeRegExp(string) {
30+
return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string
31+
}
3032
function makeSuggestion(queryName, content, {variant, name}) {
3133
return {
3234
queryName,
3335
toString() {
34-
const options = name ? `, {name: /${name.toLowerCase()}/i}` : ''
36+
const options = name
37+
? `, {name: /${escapeRegExp(name.toLowerCase())}/i}`
38+
: ''
3539
return `${variant}By${queryName}("${content}"${options})`
3640
},
3741
}

0 commit comments

Comments
 (0)