Skip to content

Commit db55959

Browse files
committed
add warning
1 parent 687b1e4 commit db55959

File tree

2 files changed

+23
-8
lines changed

2 files changed

+23
-8
lines changed

src/__tests__/matches.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,19 @@ test('matchers accept regex', () => {
1616
})
1717

1818
// https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results
19-
test('matchers recreate regex to prevent global mistakes', () => {
19+
test('a regex with the global flag consistently (re-)finds a match', () => {
2020
const regex = /ABC/g
21+
const spy = jest.spyOn(console, 'warn').mockImplementation()
22+
2123
expect(matches('ABC', node, regex, normalizer)).toBe(true)
22-
// without recreation of the regexp this would be false
2324
expect(fuzzyMatches('ABC', node, regex, normalizer)).toBe(true)
25+
26+
expect(spy).toBeCalledTimes(2)
27+
expect(spy).toHaveBeenCalledWith(
28+
`To match all elements we had to reset the lastIndex of the RegExp because the global flag is enabled. We encourage to remove the global flag from the RegExp.`,
29+
)
30+
31+
console.warn.mockClear()
2432
})
2533

2634
test('matchers accept functions', () => {

src/matches.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ function fuzzyMatches(
3636
} else if (typeof matcher === 'function') {
3737
return matcher(normalizedText, node)
3838
} else {
39-
return matcher.test(normalizedText)
39+
return matchRegExp(matcher, normalizedText)
4040
}
4141
}
4242

@@ -56,11 +56,7 @@ function matches(
5656
if (matcher instanceof Function) {
5757
return matcher(normalizedText, node)
5858
} else if (matcher instanceof RegExp) {
59-
const match = matcher.test(normalizedText)
60-
if (matcher.global) {
61-
matcher.lastIndex = 0
62-
}
63-
return match
59+
return matchRegExp(matcher, normalizedText)
6460
} else {
6561
return normalizedText === String(matcher)
6662
}
@@ -116,4 +112,15 @@ function makeNormalizer({
116112
}
117113
}
118114

115+
function matchRegExp(matcher: RegExp, text: string) {
116+
const match = matcher.test(text)
117+
if (matcher.global && matcher.lastIndex !== 0) {
118+
console.warn(
119+
`To match all elements we had to reset the lastIndex of the RegExp because the global flag is enabled. We encourage to remove the global flag from the RegExp.`,
120+
)
121+
matcher.lastIndex = 0
122+
}
123+
return match
124+
}
125+
119126
export {fuzzyMatches, matches, getDefaultNormalizer, makeNormalizer}

0 commit comments

Comments
 (0)