File tree Expand file tree Collapse file tree 2 files changed +23
-8
lines changed Expand file tree Collapse file tree 2 files changed +23
-8
lines changed Original file line number Diff line number Diff line change @@ -16,11 +16,19 @@ test('matchers accept regex', () => {
16
16
} )
17
17
18
18
// 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 ' , ( ) => {
20
20
const regex = / A B C / g
21
+ const spy = jest . spyOn ( console , 'warn' ) . mockImplementation ( )
22
+
21
23
expect ( matches ( 'ABC' , node , regex , normalizer ) ) . toBe ( true )
22
- // without recreation of the regexp this would be false
23
24
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 ( )
24
32
} )
25
33
26
34
test ( 'matchers accept functions' , ( ) => {
Original file line number Diff line number Diff line change @@ -36,7 +36,7 @@ function fuzzyMatches(
36
36
} else if ( typeof matcher === 'function' ) {
37
37
return matcher ( normalizedText , node )
38
38
} else {
39
- return matcher . test ( normalizedText )
39
+ return matchRegExp ( matcher , normalizedText )
40
40
}
41
41
}
42
42
@@ -56,11 +56,7 @@ function matches(
56
56
if ( matcher instanceof Function ) {
57
57
return matcher ( normalizedText , node )
58
58
} 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 )
64
60
} else {
65
61
return normalizedText === String ( matcher )
66
62
}
@@ -116,4 +112,15 @@ function makeNormalizer({
116
112
}
117
113
}
118
114
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
+
119
126
export { fuzzyMatches , matches , getDefaultNormalizer , makeNormalizer }
You can’t perform that action at this time.
0 commit comments