Skip to content

Commit

Permalink
explicit test for catching errors
Browse files Browse the repository at this point in the history
  • Loading branch information
hoeck committed Dec 19, 2023
1 parent 29f1a45 commit ffdfd7c
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions test/runtypeError.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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 `<value>` 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({
Expand All @@ -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 `<value>.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 `<value>` for `{"a":1,"b":"foo","c":"not-in-record-definition"}`',
)
} else {
throw e
}
}
})
})

0 comments on commit ffdfd7c

Please sign in to comment.