Skip to content

Commit 84a0a22

Browse files
committed
test: add more regex test cases
1 parent df69c33 commit 84a0a22

File tree

2 files changed

+51
-5
lines changed

2 files changed

+51
-5
lines changed

src/__tests__/matches.js

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import cases from 'jest-in-case'
12
import {fuzzyMatches, matches} from '../matches'
23

34
// unit tests for text match utils
@@ -10,12 +11,55 @@ test('matchers accept strings', () => {
1011
expect(fuzzyMatches('ABC', node, 'ABC', normalizer)).toBe(true)
1112
})
1213

13-
test('matchers accept regex', () => {
14-
expect(matches('ABC', node, /ABC/, normalizer)).toBe(true)
15-
expect(fuzzyMatches('ABC', node, /ABC/, normalizer)).toBe(true)
16-
})
14+
cases(
15+
'matchers accept regex',
16+
({textToMatch, regex}) => {
17+
expect(matches(textToMatch, node, regex, normalizer)).toBe(true)
18+
expect(fuzzyMatches(textToMatch, node, regex, normalizer)).toBe(true)
19+
},
20+
{
21+
normal: {
22+
textToMatch: 'ABC',
23+
regex: /ABC/,
24+
},
25+
global: {
26+
textToMatch: 'ABC',
27+
regex: /ABC/g,
28+
},
29+
caseInsensitive: {
30+
textToMatch: 'ABC',
31+
regex: /abc/i,
32+
},
33+
globalCaseInsensitive: {
34+
textToMatch: 'AbC',
35+
regex: /abc/gi,
36+
},
37+
multiLine: {
38+
textToMatch: `
39+
ABC`,
40+
regex: /^ABC/m,
41+
},
42+
dotAll: {
43+
textToMatch: `AB
44+
C`,
45+
regex: /AB.C/s,
46+
},
47+
unicode: {
48+
textToMatch: '\u{61}',
49+
regex: /\u{61}/u,
50+
},
51+
sticky: {
52+
textToMatch: 'ABC',
53+
regex: /ABC/y,
54+
},
55+
indecies: {
56+
textToMatch: 'ABC ABC',
57+
// eslint-disable-next-line no-empty-character-class
58+
regex: /ABC/d,
59+
},
60+
},
61+
)
1762

18-
// https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results
1963
test('matchers recreate regex to prevent global mistakes', () => {
2064
const regex = /ABC/g
2165
expect(matches('ABC', node, regex, normalizer)).toBe(true)

src/matches.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ function matches(
5656
if (matcher instanceof Function) {
5757
return matcher(normalizedText, node)
5858
} else if (matcher instanceof RegExp) {
59+
// recreate regex to prevent state on the regex instance
60+
// https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results
5961
return new RegExp(matcher).test(normalizedText)
6062
} else {
6163
return normalizedText === String(matcher)

0 commit comments

Comments
 (0)