Skip to content

fix: Prevent isMatchingPattern from failing and add tests #2543

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion packages/utils/src/string.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isRegExp } from './is';
import { isRegExp, isString } from './is';

/**
* Truncates given string to the maximum characters count
Expand Down Expand Up @@ -89,6 +89,10 @@ export function safeJoin(input: any[], delimiter?: string): string {
* @param pattern Either a regex or a string that must be contained in value
*/
export function isMatchingPattern(value: string, pattern: RegExp | string): boolean {
if (!isString(value)) {
return false;
}

if (isRegExp(pattern)) {
return (pattern as RegExp).test(value);
}
Expand Down
31 changes: 30 additions & 1 deletion packages/utils/test/string.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { truncate } from '../src/string';
import { isMatchingPattern, truncate } from '../src/string';

describe('truncate()', () => {
test('it works as expected', () => {
Expand All @@ -10,3 +10,32 @@ describe('truncate()', () => {
expect(truncate(new Array(1000).join('f'), 0)).toEqual(new Array(1000).join('f'));
});
});

describe('isMatchingPattern()', () => {
test('match using string substring', () => {
expect(isMatchingPattern('foobar', 'foobar')).toEqual(true);
expect(isMatchingPattern('foobar', 'foo')).toEqual(true);
expect(isMatchingPattern('foobar', 'bar')).toEqual(true);
expect(isMatchingPattern('foobar', 'nope')).toEqual(false);
});

test('match using regexp test', () => {
expect(isMatchingPattern('foobar', /^foo/)).toEqual(true);
expect(isMatchingPattern('foobar', /foo/)).toEqual(true);
expect(isMatchingPattern('foobar', /b.{1}r/)).toEqual(true);
expect(isMatchingPattern('foobar', /^foo$/)).toEqual(false);
});

test('should match empty pattern as true', () => {
expect(isMatchingPattern('foo', '')).toEqual(true);
expect(isMatchingPattern('bar', '')).toEqual(true);
expect(isMatchingPattern('', '')).toEqual(true);
});

test('should bail out with false when given non-string value', () => {
expect(isMatchingPattern(null, 'foo')).toEqual(false);
expect(isMatchingPattern(undefined, 'foo')).toEqual(false);
expect(isMatchingPattern({}, 'foo')).toEqual(false);
expect(isMatchingPattern([], 'foo')).toEqual(false);
});
});