|
1 |
| -import { morphism, createSchema } from '../morphism'; |
2 |
| -import { defaultFormatter, reporter, ValidationError } from './reporter'; |
| 1 | +import { morphism, createSchema, Reporter } from '../morphism'; |
| 2 | +import { defaultFormatter, reporter, ValidationError, Formatter } from './reporter'; |
3 | 3 | import { Validation } from './Validation';
|
4 | 4 |
|
5 | 5 | describe('Reporter', () => {
|
@@ -50,6 +50,49 @@ describe('Reporter', () => {
|
50 | 50 | }).toThrow('Rule max has already been used');
|
51 | 51 | });
|
52 | 52 |
|
| 53 | + it('should allow to use a reporter with a custom formatter', () => { |
| 54 | + interface Target { |
| 55 | + t1: string; |
| 56 | + } |
| 57 | + const formatter: Formatter = error => { |
| 58 | + const { expect, targetProperty, value } = error; |
| 59 | + return `Expected ${expect} but received ${value} for property ${targetProperty}`; |
| 60 | + }; |
| 61 | + const reporter = new Reporter(formatter); |
| 62 | + |
| 63 | + const schema = createSchema<Target>({ t1: { path: 's1', validation: Validation.string() } }); |
| 64 | + const result = morphism(schema, { s1: 1234 }); |
| 65 | + const error = new ValidationError({ targetProperty: 't1', value: 1234, expect: 'value to be typeof string' }); |
| 66 | + const message = formatter(error); |
| 67 | + const errors = reporter.report(result); |
| 68 | + expect(errors).not.toBeNull(); |
| 69 | + if (errors) { |
| 70 | + expect(errors[0]).toBe(message); |
| 71 | + } |
| 72 | + }); |
| 73 | + |
| 74 | + it('should allow to use a reporter with a custom formatter via schema options', () => { |
| 75 | + interface Target { |
| 76 | + t1: string; |
| 77 | + } |
| 78 | + const formatter: Formatter = error => { |
| 79 | + const { expect, targetProperty, value } = error; |
| 80 | + return `Expected ${expect} but received ${value} for property ${targetProperty}`; |
| 81 | + }; |
| 82 | + const reporter = new Reporter(formatter); |
| 83 | + |
| 84 | + const schema = createSchema<Target>( |
| 85 | + { t1: { path: 's1', validation: Validation.string() } }, |
| 86 | + { validation: { throw: true, reporter } } |
| 87 | + ); |
| 88 | + |
| 89 | + const error = new ValidationError({ targetProperty: 't1', value: 1234, expect: 'value to be typeof string' }); |
| 90 | + const message = formatter(error); |
| 91 | + expect(() => { |
| 92 | + morphism(schema, { s1: 1234 }); |
| 93 | + }).toThrow(message); |
| 94 | + }); |
| 95 | + |
53 | 96 | describe('string', () => {
|
54 | 97 | it('should report error on string undefined', () => {
|
55 | 98 | interface S {
|
|
0 commit comments