Skip to content

Commit 531bbfe

Browse files
authored
fix: Prevent isMatchingPattern from failing and add tests (getsentry#2543)
1 parent d32283d commit 531bbfe

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

packages/utils/src/string.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { isRegExp } from './is';
1+
import { isRegExp, isString } from './is';
22

33
/**
44
* Truncates given string to the maximum characters count
@@ -89,6 +89,10 @@ export function safeJoin(input: any[], delimiter?: string): string {
8989
* @param pattern Either a regex or a string that must be contained in value
9090
*/
9191
export function isMatchingPattern(value: string, pattern: RegExp | string): boolean {
92+
if (!isString(value)) {
93+
return false;
94+
}
95+
9296
if (isRegExp(pattern)) {
9397
return (pattern as RegExp).test(value);
9498
}

packages/utils/test/string.test.ts

+30-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { truncate } from '../src/string';
1+
import { isMatchingPattern, truncate } from '../src/string';
22

33
describe('truncate()', () => {
44
test('it works as expected', () => {
@@ -10,3 +10,32 @@ describe('truncate()', () => {
1010
expect(truncate(new Array(1000).join('f'), 0)).toEqual(new Array(1000).join('f'));
1111
});
1212
});
13+
14+
describe('isMatchingPattern()', () => {
15+
test('match using string substring', () => {
16+
expect(isMatchingPattern('foobar', 'foobar')).toEqual(true);
17+
expect(isMatchingPattern('foobar', 'foo')).toEqual(true);
18+
expect(isMatchingPattern('foobar', 'bar')).toEqual(true);
19+
expect(isMatchingPattern('foobar', 'nope')).toEqual(false);
20+
});
21+
22+
test('match using regexp test', () => {
23+
expect(isMatchingPattern('foobar', /^foo/)).toEqual(true);
24+
expect(isMatchingPattern('foobar', /foo/)).toEqual(true);
25+
expect(isMatchingPattern('foobar', /b.{1}r/)).toEqual(true);
26+
expect(isMatchingPattern('foobar', /^foo$/)).toEqual(false);
27+
});
28+
29+
test('should match empty pattern as true', () => {
30+
expect(isMatchingPattern('foo', '')).toEqual(true);
31+
expect(isMatchingPattern('bar', '')).toEqual(true);
32+
expect(isMatchingPattern('', '')).toEqual(true);
33+
});
34+
35+
test('should bail out with false when given non-string value', () => {
36+
expect(isMatchingPattern(null, 'foo')).toEqual(false);
37+
expect(isMatchingPattern(undefined, 'foo')).toEqual(false);
38+
expect(isMatchingPattern({}, 'foo')).toEqual(false);
39+
expect(isMatchingPattern([], 'foo')).toEqual(false);
40+
});
41+
});

0 commit comments

Comments
 (0)