|
| 1 | +import { morphism, createSchema } from '../morphism'; |
| 2 | +import { string } from './validators'; |
| 3 | +import { number } from './validators'; |
| 4 | +import { formatter, reporter } from './reporter'; |
| 5 | +import { getSymbolName } from '../helpers'; |
| 6 | + |
| 7 | +describe('Reporter', () => { |
| 8 | + describe('Formatter', () => { |
| 9 | + it('should format a ValidationError to human readable message', () => { |
| 10 | + const targetProperty = 'targetProperty'; |
| 11 | + const value = undefined; |
| 12 | + const type = string; |
| 13 | + const message = formatter({ targetProperty, value, type }); |
| 14 | + expect(message).toEqual( |
| 15 | + `Invalid value ${value} supplied to : [⚠️ Schema With Type] at property ${targetProperty}. Expecting type ${getSymbolName(type)}` |
| 16 | + ); |
| 17 | + }); |
| 18 | + }); |
| 19 | + describe('Validation', () => { |
| 20 | + it('should report error on string undefined', () => { |
| 21 | + interface S { |
| 22 | + s1: string; |
| 23 | + } |
| 24 | + interface T { |
| 25 | + t1: string; |
| 26 | + } |
| 27 | + |
| 28 | + const schema = createSchema<T, S>({ t1: { path: 's1', fn: val => val, type: string } }); |
| 29 | + const result = morphism(schema, JSON.parse('{}')); |
| 30 | + const message = formatter({ targetProperty: 't1', value: undefined, type: string }); |
| 31 | + const errors = reporter(result); |
| 32 | + |
| 33 | + expect(errors.length).toEqual(1); |
| 34 | + expect(errors[0]).toBe(message); |
| 35 | + }); |
| 36 | + |
| 37 | + it('should report error on number undefined', () => { |
| 38 | + interface S { |
| 39 | + s1: string; |
| 40 | + } |
| 41 | + interface T { |
| 42 | + t1: number; |
| 43 | + } |
| 44 | + |
| 45 | + const schema = createSchema<T, S>({ t1: { path: 's1', fn: val => val, type: number } }); |
| 46 | + const result = morphism(schema, JSON.parse('{}')); |
| 47 | + const message = formatter({ targetProperty: 't1', value: undefined, type: number }); |
| 48 | + const errors = reporter(result); |
| 49 | + |
| 50 | + expect(errors.length).toEqual(1); |
| 51 | + expect(errors[0]).toBe(message); |
| 52 | + }); |
| 53 | + |
| 54 | + it('should parse number from string', () => { |
| 55 | + interface S { |
| 56 | + s1: string; |
| 57 | + } |
| 58 | + interface T { |
| 59 | + t1: number; |
| 60 | + } |
| 61 | + |
| 62 | + const schema = createSchema<T, S>({ t1: { path: 's1', fn: val => val, type: number } }); |
| 63 | + const result = morphism(schema, JSON.parse('{ "s1": "1234" }')); |
| 64 | + const errors = reporter(result); |
| 65 | + |
| 66 | + expect(errors.length).toEqual(0); |
| 67 | + expect(result).toEqual({ t1: 1234 }); |
| 68 | + }); |
| 69 | + }); |
| 70 | +}); |
0 commit comments