File tree 2 files changed +29
-2
lines changed
2 files changed +29
-2
lines changed Original file line number Diff line number Diff line change @@ -15,6 +15,22 @@ test('matchers accept regex', () => {
15
15
expect ( fuzzyMatches ( 'ABC' , node , / A B C / , normalizer ) ) . toBe ( true )
16
16
} )
17
17
18
+ // https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results
19
+ test ( 'a regex with the global flag consistently (re-)finds a match' , ( ) => {
20
+ const regex = / A B C / g
21
+ const spy = jest . spyOn ( console , 'warn' ) . mockImplementation ( )
22
+
23
+ expect ( matches ( 'ABC' , node , regex , normalizer ) ) . toBe ( true )
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 ( )
32
+ } )
33
+
18
34
test ( 'matchers accept functions' , ( ) => {
19
35
expect ( matches ( 'ABC' , node , text => text === 'ABC' , normalizer ) ) . toBe ( true )
20
36
expect ( fuzzyMatches ( 'ABC' , node , text => text === 'ABC' , normalizer ) ) . toBe (
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,7 +56,7 @@ function matches(
56
56
if ( matcher instanceof Function ) {
57
57
return matcher ( normalizedText , node )
58
58
} else if ( matcher instanceof RegExp ) {
59
- return matcher . test ( normalizedText )
59
+ return matchRegExp ( matcher , normalizedText )
60
60
} else {
61
61
return normalizedText === String ( matcher )
62
62
}
@@ -111,4 +111,15 @@ function makeNormalizer({
111
111
return normalizer
112
112
}
113
113
114
+ function matchRegExp ( matcher : RegExp , text : string ) {
115
+ const match = matcher . test ( text )
116
+ if ( matcher . global && matcher . lastIndex !== 0 ) {
117
+ console . warn (
118
+ `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.` ,
119
+ )
120
+ matcher . lastIndex = 0
121
+ }
122
+ return match
123
+ }
124
+
114
125
export { fuzzyMatches , matches , getDefaultNormalizer , makeNormalizer }
You can’t perform that action at this time.
0 commit comments