Skip to content

Commit

Permalink
test: add more regex test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
timdeschryver committed Mar 22, 2022
1 parent df69c33 commit 84a0a22
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 5 deletions.
54 changes: 49 additions & 5 deletions src/__tests__/matches.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import cases from 'jest-in-case'
import {fuzzyMatches, matches} from '../matches'

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

test('matchers accept regex', () => {
expect(matches('ABC', node, /ABC/, normalizer)).toBe(true)
expect(fuzzyMatches('ABC', node, /ABC/, normalizer)).toBe(true)
})
cases(
'matchers accept regex',
({textToMatch, regex}) => {
expect(matches(textToMatch, node, regex, normalizer)).toBe(true)
expect(fuzzyMatches(textToMatch, node, regex, normalizer)).toBe(true)
},
{
normal: {
textToMatch: 'ABC',
regex: /ABC/,
},
global: {
textToMatch: 'ABC',
regex: /ABC/g,
},
caseInsensitive: {
textToMatch: 'ABC',
regex: /abc/i,
},
globalCaseInsensitive: {
textToMatch: 'AbC',
regex: /abc/gi,
},
multiLine: {
textToMatch: `
ABC`,
regex: /^ABC/m,
},
dotAll: {
textToMatch: `AB
C`,
regex: /AB.C/s,
},
unicode: {
textToMatch: '\u{61}',
regex: /\u{61}/u,
},
sticky: {
textToMatch: 'ABC',
regex: /ABC/y,
},
indecies: {
textToMatch: 'ABC ABC',
// eslint-disable-next-line no-empty-character-class
regex: /ABC/d,
},
},
)

// https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results
test('matchers recreate regex to prevent global mistakes', () => {
const regex = /ABC/g
expect(matches('ABC', node, regex, normalizer)).toBe(true)
Expand Down
2 changes: 2 additions & 0 deletions src/matches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ function matches(
if (matcher instanceof Function) {
return matcher(normalizedText, node)
} else if (matcher instanceof RegExp) {
// recreate regex to prevent state on the regex instance
// https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results
return new RegExp(matcher).test(normalizedText)
} else {
return normalizedText === String(matcher)
Expand Down

0 comments on commit 84a0a22

Please sign in to comment.