-
Notifications
You must be signed in to change notification settings - Fork 330
/
refinement.ts
75 lines (65 loc) · 2.37 KB
/
refinement.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
import * as assert from 'assert'
import * as t from '../../src/index'
import { assertSuccess, assertFailure, assertStrictEqual, IntegerFromString, NumberFromString } from './helpers'
describe('refinement', () => {
describe('name', () => {
it('should assign a default name', () => {
const T = t.refinement(t.number, (n) => n >= 0)
assert.strictEqual(T.name, '(number | <function1>)')
})
it('should accept a name', () => {
const T = t.refinement(t.number, (n) => n >= 0, 'T')
assert.strictEqual(T.name, 'T')
})
})
describe('is', () => {
it('should check a isomorphic value', () => {
const T = t.Integer
assert.strictEqual(T.is(1.2), false)
assert.strictEqual(T.is('a'), false)
assert.strictEqual(T.is(1), true)
})
it('should check a prismatic value', () => {
const T = t.refinement(NumberFromString, (n) => n % 1 === 0)
assert.strictEqual(T.is(1.2), false)
assert.strictEqual(T.is('a'), false)
assert.strictEqual(T.is(1), true)
})
})
describe('decode', () => {
it('should succeed validating a valid value', () => {
const T = t.refinement(t.number, (n) => n >= 0)
assertSuccess(T.decode(0))
assertSuccess(T.decode(1))
})
it('should return the same reference if validation succeeded', () => {
const T = t.refinement(
// tslint:disable-next-line: deprecation
t.Dictionary,
() => true
)
const value = {}
assertStrictEqual(T.decode(value), value)
})
it('should fail validating an invalid value', () => {
const T = t.Integer
assertFailure(T, 'a', ['Invalid value "a" supplied to : Integer'])
assertFailure(T, 1.2, ['Invalid value 1.2 supplied to : Integer'])
})
it('should fail with the last deserialized value', () => {
const T = IntegerFromString
assertFailure(T, 'a', ['cannot parse to a number'])
assertFailure(T, '1.2', ['Invalid value 1.2 supplied to : IntegerFromString'])
})
})
describe('encode', () => {
it('should encode a prismatic value', () => {
const T = t.refinement(t.array(NumberFromString), () => true)
assert.deepStrictEqual(T.encode([1]), ['1'])
})
it('should return the same reference while encoding', () => {
const T = t.refinement(t.array(t.number), () => true)
assert.strictEqual(T.encode, t.identity)
})
})
})