javascript / expert
Snippet
Testing Exception Handling in SvelteKit Page Load Functions
Unit testing SvelteKit `load` functions requires crafting synthetic server event objects (`ServerLoadEvent`) and capturing error objects thrown by SvelteKit's `error()` helper. Using `try/catch` alongside `expect.unreachable()` ensures that authorization failures properly throw expected HTTP status codes.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { error } from '@sveltejs/kit';import { expect, test, vi } from 'vitest';import { load } from './+page.js';vi.mock('$app/navigation', () => ({goto: vi.fn()}));test('throws HttpError 401 when authentication context is missing', async () => {const mockEvent = {locals: { user: null },params: { id: '123' },fetch: vi.fn()};try {await load(mockEvent);expect.unreachable('Load function should have thrown HttpError');} catch (err) {expect(err.status).toBe(401);expect(err.body.message).toBe('Unauthorized access');}});
svelte
Breakdown
1
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
Mocks SvelteKit internal navigation modules to prevent module resolution errors in unit test environments.
2
const mockEvent = { locals: { user: null }, params: { id: '123' }, fetch: vi.fn() };
Constructs a mocked event payload simulating an unauthenticated request context.
3
expect.unreachable('Load function should have thrown HttpError');
Fails the test explicitly if the tested load function executes without throwing an exception.
4
expect(err.status).toBe(401);
Validates that the caught HttpError exception matches the expected 401 status payload.