Skip to content

Commit

Permalink
feat: Add isString
Browse files Browse the repository at this point in the history
  • Loading branch information
NiGhTTraX committed May 30, 2020
1 parent cc5b0a8 commit 6d5980f
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
40 changes: 39 additions & 1 deletion src/matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,14 +112,52 @@ const isNumber = (): Matcher<number> =>
toJSON: () => 'isNumber',
} as any);

/**
* Match a string, potentially by a pattern.
*
* @param matching The string has to match this RegExp.
* @param containing The string has to contain this substring.
*
* @example
* const fn = mock<(x: string, y: string) => number>();
* when(fn(It.isString(), It.isString({ containing: 'bar' }).returns(42);
*
* instance(fn)('foo', 'baz') // throws
* instance(fn)('foo', 'bar') === 42
*/
const isString = ({
matching,
containing,
}: { matching?: RegExp; containing?: string } = {}): Matcher<string> => {
if (matching && containing) {
throw new Error('You can only pass `matching` or `containing`, not both.');
}

return {
__isMatcher: true,
matches: (arg: any) => {
if (typeof arg !== 'string') {
return false;
}

if (containing) {
return arg.indexOf(containing) !== -1;
}

return matching?.test(arg) ?? true;
},
toJSON: () => 'isString',
} as any;
};

/**
* Contains argument matchers that can be used to ignore arguments in an
* expectation or to match complex arguments.
*/
// TODO: add isStringContaining
export const It = {
isAny,
matches,
isObjectContaining,
isNumber,
isString,
};
30 changes: 30 additions & 0 deletions tests/matcher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,36 @@ describe('It', () => {
});
});

describe('isString', () => {
it('should match any string', () => {
expect(It.isString().matches('foobar')).toBeTruthy();
});

it('should match the empty string', () => {
expect(It.isString().matches('')).toBeTruthy();
});

it('should not match numbers', () => {
expect(It.isString().matches(10e2)).toBeFalsy();
});

it('should match a string based on the given pattern', () => {
expect(It.isString({ matching: /foo/ }).matches('foo')).toBeTruthy();
expect(It.isString({ matching: /foo/ }).matches('bar')).toBeFalsy();
});

it('should match a string containing the given substring', () => {
expect(It.isString({ containing: 'foo' }).matches('foobar')).toBeTruthy();
expect(It.isString({ containing: 'baz' }).matches('foobar')).toBeFalsy();
});

it('should throw if more than one pattern given', () => {
expect(() =>
It.isString({ matching: /foo/, containing: 'bar' })
).toThrow();
});
});

describe('matches', () => {
it('should support custom predicates', () => {
expect(It.matches(() => true).matches(':irrelevant:')).toBeTruthy();
Expand Down

0 comments on commit 6d5980f

Please sign in to comment.