Browse Source

Add `string.oneOf` - fixes #80 (#87)

master
Sam Verschueren 7 years ago
committed by Sindre Sorhus
parent
commit
b1af8ad275
  1. 21
      source/lib/predicates/string.ts
  2. 8
      source/test/string.ts

21
source/lib/predicates/string.ts

@ -93,6 +93,27 @@ export class StringPredicate extends Predicate<string> {
}); });
} }
/**
* 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. * Test a string to be empty.
*/ */

8
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`'); 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 => { test('string.empty', t => {
t.notThrows(() => m('', m.string.empty)); t.notThrows(() => m('', m.string.empty));
t.throws(() => m('foo' as any, m.string.empty), 'Expected string to be empty, got `foo`'); t.throws(() => m('foo' as any, m.string.empty), 'Expected string to be empty, got `foo`');

Loading…
Cancel
Save