diff --git a/test/runtypeError.test.ts b/test/runtypeError.test.ts index 7e0a429..03115b1 100644 --- a/test/runtypeError.test.ts +++ b/test/runtypeError.test.ts @@ -2,7 +2,7 @@ import { st } from './helpers' describe('getFormattedError', () => { it('should return the correctly formatted error string', () => { - const recordResult: any = st.use( + const recordResult = st.use( st.record({ a: st.integer(), b: st.string(), @@ -13,11 +13,16 @@ describe('getFormattedError', () => { c: 'not-in-record-definition', }, ) + + if (recordResult.ok === true) { + throw new Error() + } + expect(st.getFormattedError(recordResult.error)).toEqual( 'invalid keys in record: ["c"] at `` for `{"a":1,"b":"foo","c":"not-in-record-definition"}`', ) - const nestedRecordResult: any = st.use( + const nestedRecordResult = st.use( st.record({ a: st.integer(), d: st.record({ @@ -26,8 +31,37 @@ describe('getFormattedError', () => { }), { a: 1, d: { e: 'foo', f: 'not-in-record-definition' } }, ) + + if (nestedRecordResult.ok === true) { + throw new Error() + } + expect(st.getFormattedError(nestedRecordResult.error)).toEqual( 'invalid keys in record: ["f"] at `.d` for `{"e":"foo","f":"not-in-record-definition"}`', ) }) + + it('should work on exception-errors', () => { + const runtype = st.record({ + a: st.integer(), + b: st.string(), + }) + + try { + runtype({ + a: 1, + b: 'foo', + c: 'not-in-record-definition', + }) + expect(true).toBe(false) + } catch (e) { + if (st.isRuntypeError(e)) { + expect(st.getFormattedError(e)).toEqual( + 'RuntypeError: invalid keys in record: ["c"] at `` for `{"a":1,"b":"foo","c":"not-in-record-definition"}`', + ) + } else { + throw e + } + } + }) })