From b1af8ad27518e5f708e31237a32f2e1f9e95f3ac Mon Sep 17 00:00:00 2001 From: Sam Verschueren Date: Wed, 30 May 2018 08:07:38 +0200 Subject: [PATCH] Add `string.oneOf` - fixes #80 (#87) --- source/lib/predicates/string.ts | 21 +++++++++++++++++++++ source/test/string.ts | 8 ++++++++ 2 files changed, 29 insertions(+) diff --git a/source/lib/predicates/string.ts b/source/lib/predicates/string.ts index f4f97cc..7fae6d1 100644 --- a/source/lib/predicates/string.ts +++ b/source/lib/predicates/string.ts @@ -93,6 +93,27 @@ export class StringPredicate extends Predicate { }); } + /** + * Test if the string is an element of the provided list. + * + * @param list List of possible values. + */ + oneOf(list: string[]) { + return this.addValidator({ + message: (value, label) => { + let printedList = JSON.stringify(list); + + if (list.length > 10) { + const overflow = list.length - 10; + printedList = JSON.stringify(list.slice(0, 10)).replace(/]$/, `,…+${overflow} more]`); + } + + return `Expected ${label} to be one of \`${printedList}\`, got \`${value}\``; + }, + validator: value => list.includes(value) + }); + } + /** * Test a string to be empty. */ diff --git a/source/test/string.ts b/source/test/string.ts index f8f9075..ea494a4 100644 --- a/source/test/string.ts +++ b/source/test/string.ts @@ -56,6 +56,14 @@ test('string.includes', t => { t.throws(() => m('foo' as any, m.string.includes('bar')), 'Expected string to include `bar`, got `foo`'); }); +test('string.oneOf', t => { + t.notThrows(() => m('foo', m.string.oneOf(['foo', 'bar']))); + t.throws(() => m('foo', m.string.oneOf(['unicorn', 'rainbow'])), 'Expected string to be one of `["unicorn","rainbow"]`, got `foo`'); + t.throws(() => m('foo', m.string.oneOf(['unicorn', 'rainbow']).label('hello')), 'Expected string `hello` to be one of `["unicorn","rainbow"]`, got `foo`'); + t.throws(() => m('foo', m.string.oneOf(['a', 'b', 'c', 'd', 'e'])), 'Expected string to be one of `["a","b","c","d","e"]`, got `foo`'); + t.throws(() => m('foo', m.string.oneOf(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'])), 'Expected string to be one of `["1","2","3","4","5","6","7","8","9","10",…+3 more]`, got `foo`'); +}); + test('string.empty', t => { t.notThrows(() => m('', m.string.empty)); t.throws(() => m('foo' as any, m.string.empty), 'Expected string to be empty, got `foo`');