-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidatedString.test.ts
79 lines (64 loc) · 2.45 KB
/
ValidatedString.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { assertEquals, assertThrows } from '@std/assert';
import { ValidatedString } from './ValidatedString.ts';
Deno.test('ValidatedString - basic validation with try()', () =>
{
const isHello = (s: string) => s === 'hello';
const { factory } = ValidatedString.create(isHello);
const validResult = factory.try('hello');
assertEquals(validResult, 'hello');
const invalidResult = factory.try('hi');
assertEquals(invalidResult, undefined);
});
Deno.test('ValidatedString - assert() with valid input', () =>
{
const isHello = (s: string) => s === 'hello';
const { factory } = ValidatedString.create(isHello);
const result = factory.assert('hello');
assertEquals(result, 'hello');
});
Deno.test('ValidatedString - assert() with invalid input throws error', () =>
{
const isHello = (s: string) => s === 'hello';
const { factory } = ValidatedString.create(isHello);
assertThrows(
() => factory.assert('hi'),
Error,
`Invalid string did not pass validation: Supplied value "hi" is not valid for validator "(s)=>s === 'hello'..."`,
);
});
Deno.test('ValidatedString - custom name and description in error message', () =>
{
const isHello = (s: string) => s === 'hello';
const { factory } = ValidatedString.create(isHello, {
name: 'HelloString',
description: "must be exactly 'hello'",
});
assertThrows(
() => factory.assert('hi'),
Error,
'Invalid string did not pass validation: Supplied value "hi" is not valid for validator "HelloString" (must be exactly \'hello\').',
);
});
Deno.test('ValidatedString - long input string gets truncated in error', () =>
{
const isShort = (s: string) => s.length < 10;
const { factory } = ValidatedString.create(isShort);
const longString = 'a'.repeat(100);
const expectedTruncated = 'a'.repeat(64) + '...';
assertThrows(
() => factory.assert(longString),
Error,
`Invalid string did not pass validation: Supplied value "${expectedTruncated}" is not valid for validator "(s)=>s.length < 10..."`,
);
});
Deno.test('ValidatedString - type safety', () =>
{
const isHello = (s: string) => s === 'hello';
const { factory, type } = ValidatedString.create(isHello);
type HelloString = typeof type;
// This line would cause a TypeScript compilation error if uncommented:
// @ts-expect-error Type 'string' is not assignable to type 'HelloString'.
const _invalid: HelloString = 'hi';
const valid: HelloString = factory.assert('hello');
assertEquals(valid, 'hello');
});