|
6 | 6 | number,
|
7 | 7 | boolean,
|
8 | 8 | anyJson,
|
| 9 | + unknownJson, |
9 | 10 | constant,
|
10 | 11 | object,
|
11 | 12 | array,
|
@@ -95,13 +96,42 @@ describe('boolean', () => {
|
95 | 96 | });
|
96 | 97 |
|
97 | 98 | describe('anyJson', () => {
|
98 |
| - it('can be used in other decoders', () => { |
99 |
| - const json: any = [1, true, 2, 3, 'five', 4, []]; |
100 |
| - const jsonArray: any[] = Result.withDefault([], array(anyJson()).run(json)); |
101 |
| - const successes: Result.Ok<number>[] = jsonArray.map(number().run).filter(Result.isOk); |
102 |
| - const numbers: number[] = successes.map(ok => ok.result); |
| 99 | + it('bypasses type validation', () => { |
| 100 | + // in a real use case this could be a deeply nested object |
| 101 | + type ComplexType = number; |
103 | 102 |
|
104 |
| - expect(numbers).toEqual([1, 2, 3, 4]); |
| 103 | + interface User { |
| 104 | + name: string; |
| 105 | + complexUserData: ComplexType; |
| 106 | + } |
| 107 | + |
| 108 | + const userDecoder: Decoder<User> = object({ |
| 109 | + name: string(), |
| 110 | + complexUserData: anyJson() |
| 111 | + }); |
| 112 | + |
| 113 | + expect(userDecoder.run({name: 'Wanda', complexUserData: true})).toEqual({ |
| 114 | + ok: true, |
| 115 | + result: {name: 'Wanda', complexUserData: true} |
| 116 | + }); |
| 117 | + |
| 118 | + expect(userDecoder.run({name: 'Willard', complexUserData: 'trash data'})).toEqual({ |
| 119 | + ok: true, |
| 120 | + result: {name: 'Willard', complexUserData: 'trash data'} |
| 121 | + }); |
| 122 | + |
| 123 | + expect(userDecoder.run({name: 73, complexUserData: []})).toMatchObject({ |
| 124 | + ok: false, |
| 125 | + error: {at: 'input.name', message: 'expected a string, got a number'} |
| 126 | + }); |
| 127 | + }); |
| 128 | +}); |
| 129 | + |
| 130 | +describe('unknownJson', () => { |
| 131 | + it('accepts any values', () => { |
| 132 | + expect(unknownJson().run(1)).toEqual({ok: true, result: 1}); |
| 133 | + expect(unknownJson().run(false)).toEqual({ok: true, result: false}); |
| 134 | + expect(unknownJson().run({boots: 'n cats'})).toEqual({ok: true, result: {boots: 'n cats'}}); |
105 | 135 | });
|
106 | 136 | });
|
107 | 137 |
|
|
0 commit comments