Skip to content

Commit 5ab76de

Browse files
authored
test: add tests for error-handler (#1056)
1 parent 2273d3b commit 5ab76de

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@
114114
"@vue/test-utils": "2.4.6",
115115
"axe-core": "4.11.1",
116116
"fast-check": "4.5.3",
117+
"h3": "1.15.5",
117118
"knip": "5.83.0",
118119
"lint-staged": "16.2.7",
119120
"oxfmt": "0.27.0",

pnpm-lock.yaml

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { createError } from 'h3'
3+
import * as v from 'valibot'
4+
import { handleApiError } from '../../../../server/utils/error-handler'
5+
6+
describe('handleApiError', () => {
7+
const fallback = { message: 'Something went wrong', statusCode: 500 }
8+
9+
it('re-throws H3 errors as-is', () => {
10+
const h3Err = createError({ statusCode: 404, message: 'Not found' })
11+
12+
expect(() => handleApiError(h3Err, fallback)).toThrow(h3Err)
13+
})
14+
15+
it('throws a 404 with the first issue message for valibot errors', () => {
16+
const schema = v.object({ name: v.pipe(v.string(), v.minLength(1, 'Name is required')) })
17+
18+
let valibotError: unknown
19+
try {
20+
v.parse(schema, { name: '' })
21+
} catch (e) {
22+
valibotError = e
23+
}
24+
25+
expect(() => handleApiError(valibotError, fallback)).toThrow(
26+
expect.objectContaining({ statusCode: 404, message: 'Name is required' }),
27+
)
28+
})
29+
30+
it('throws a fallback error with the given statusCode and message', () => {
31+
expect(() =>
32+
handleApiError(new Error('unexpected'), { message: 'Bad gateway', statusCode: 502 }),
33+
).toThrow(expect.objectContaining({ statusCode: 502, message: 'Bad gateway' }))
34+
})
35+
36+
it('defaults fallback statusCode to 502 when not provided', () => {
37+
expect(() => handleApiError('some string error', { message: 'Upstream failed' })).toThrow(
38+
expect.objectContaining({ statusCode: 502, message: 'Upstream failed' }),
39+
)
40+
})
41+
42+
it('uses the custom fallback statusCode when provided', () => {
43+
expect(() => handleApiError(null, { message: 'Service unavailable', statusCode: 503 })).toThrow(
44+
expect.objectContaining({ statusCode: 503, message: 'Service unavailable' }),
45+
)
46+
})
47+
})

0 commit comments

Comments
 (0)