@@ -4,15 +4,15 @@ import {
44 bigint ,
55 bool ,
66 Decoder ,
7- DecoderError ,
7+ DecoderError , enumerator ,
88 field ,
99 float ,
1010 int ,
1111 nullable ,
1212 number ,
1313 optional ,
14- string ,
15- } from ' ./json-decode' ;
14+ string
15+ } from " ./json-decode" ;
1616
1717describe ( 'bool' , ( ) => {
1818 it ( 'decodes a boolean' , ( ) => {
@@ -125,6 +125,55 @@ describe('nullable', () => {
125125 } ) ;
126126} ) ;
127127
128+ describe ( 'enumerator' , ( ) => {
129+
130+ describe ( 'when the enum is a string enum' , ( ) => {
131+ enum Choice {
132+ carrot = 'carrot' ,
133+ stick = 'stick'
134+ }
135+
136+ it ( 'decodes the enum' , ( ) => {
137+ expect ( enumerator ( Choice ) ( 'carrot' ) ) . toEqual ( Choice . carrot ) ;
138+ } ) ;
139+
140+ it ( 'throws when the value is not a member of the enum' , ( ) => {
141+ expect ( ( ) => enumerator ( Choice ) ( 'banana' ) ) . toThrowError ( DecoderError ) ;
142+ } ) ;
143+ } ) ;
144+
145+ describe ( 'when the enum is a numeric enum' , ( ) => {
146+ enum Choice {
147+ carrot = 0 ,
148+ stick = 1
149+ }
150+
151+ it ( 'decodes the enum' , ( ) => {
152+ expect ( enumerator ( Choice ) ( 0 ) ) . toEqual ( Choice . carrot ) ;
153+ } ) ;
154+
155+ it ( 'throws when the value is not a member of the enum' , ( ) => {
156+ expect ( ( ) => enumerator ( Choice ) ( 'banana' ) ) . toThrowError ( DecoderError ) ;
157+ } ) ;
158+ } ) ;
159+
160+
161+ describe ( 'when the enum has no values assigned' , ( ) => {
162+ enum Choice {
163+ carrot ,
164+ stick
165+ }
166+
167+ it ( 'decodes the enum using the value' , ( ) => {
168+ expect ( enumerator ( Choice ) ( 1 ) ) . toEqual ( Choice . stick ) ;
169+ } ) ;
170+
171+ it ( 'throws when the value is not a member of the enum' , ( ) => {
172+ expect ( ( ) => enumerator ( Choice ) ( 3 ) ) . toThrowError ( DecoderError ) ;
173+ } ) ;
174+ } ) ;
175+ } )
176+
128177describe ( 'decoding a complex object' , ( ) => {
129178 type Blob = {
130179 name : string ;
0 commit comments