SvelteKit 16 🧡 Testing SvelteKit Apps — Unit-testing load functions, actions, and endpoints with Vitest, plus E2E testing with Playwright
Testing SvelteKit applications requires a hybrid strategy that addresses two distinct layers: the server-side logic (where you handle data and auth) and the browser interaction layer (where you verify the UI). Because SvelteKit’s load functions and actions rely on the RequestEvent object—which is tied to the internal framework lifecycle—they cannot be tested in total isolation without mocking or refactoring.
The most effective testing architecture involves extracting complex business logic into pure, testable functions, then using Vitest to verify that logic in isolation. For the integration and “glue” code, you rely on Playwright, which drives a real browser to interact with your site as a user would. This ensures that even if your individual units work, the entire chain—from database fetch to DOM render—remains robust and error-free.
This chapter covers the strategy for unit testing pure server logic, the methodology for mocking SvelteKit context for Vitest, and the implementation of automated browser tests using Playwright.
Key point: Unit testing should focus on pure business logic extracted from load functions and actions; use Playwright for E2E integration tests to verify that cookies, redirects, and state changes behave correctly in a real browser environment.
Why testing SvelteKit apps is unique
The RequestEvent dependency. load functions and actions receive a RequestEvent object containing cookies, locals, and request data. These are runtime objects provided by SvelteKit, making it difficult to execute the function directly without a mock.
The “Glue” code problem. Most server-side functions in SvelteKit act as “glue” between a database and the UI. Testing them requires simulating the network request and the response lifecycle, which is overkill for a unit test.
The client-server integration gap. A unit test might pass, but if the load data doesn’t match the component’s expected interface or if the serialization fails, the app will crash. E2E tests bridge this gap.
The state propagation requirement. In Svelte 5, tests must account for the reactive lifecycle of runes. If your component relies on context providers, tests must be able to wrap the component in those providers.
The browser environment dependency. E2E testing is the only way to reliably verify that your +page.svelte components correctly handle the data returned by the server, especially when animations and dynamic DOM updates are involved.
a. Unit testing with Vitest: The extraction pattern
The best way to test load functions and actions is to avoid testing them directly. Instead, extract your logic into “Service” or “Utility” functions that take plain objects as arguments. These are easy to test with Vitest because they have no framework dependencies.
// lib/server/auth.ts
export function validateSession(session: string) {
return session === 'secret-token';
}
// +page.server.ts
export const load = ({ cookies }) => {
return { isValid: validateSession(cookies.get('session') || '') };
};
You can now test validateSession with Vitest without mocking anything. If you must test the SvelteKit-specific logic, create a partial mock of the RequestEvent using vi.mock or a factory function.
b. Mocking the RequestEvent
When you need to test a function that does depend on SvelteKit’s event object, create a factory that generates a partial mock. This keeps your tests clean and focuses on the specific properties the function uses (like params or locals).
// test/mocks.ts
export const createMockEvent = (overrides = {}) => ({
cookies: { get: vi.fn(), set: vi.fn() },
locals: {},
params: {},
...overrides
}) as any;
// test/action.test.ts
const event = createMockEvent({ params: { id: '1' } });
await actions.default(event);
This factory approach allows you to inject exactly what your test needs, ensuring that your test code remains readable and decoupled from the framework’s internal complexities.
c. E2E testing with Playwright
Playwright is the industry standard for SvelteKit E2E tests because it launches a real browser, handles hydration, and executes the actual JavaScript bundled by Vite. This is the only way to verify that your +error.svelte pages, redirect() calls, and cookie-based authentication are working correctly for the user.
// tests/test.ts
import { expect, test } from '@playwright/test';
test('login flow works', async ({ page }) => {
await page.goto('/login');
await page.fill('input[name="user"]', 'admin');
await page.click('button');
await expect(page).toHaveURL('/dashboard');
});
Playwright tests treat your application as a “black box,” making them less susceptible to internal refactoring but more effective at catching regressions in the user experience.
Complete Example Session
// ============================================
// PART 1: PURE UTILITY TEST (VITEST)
// ============================================
import { expect, test } from 'vitest';
import { calculateTotal } from '$lib/cart';
test('cart math', () => {
expect(calculateTotal([10, 20])).toBe(30);
});
// ============================================
// PART 2: SERVER ACTION MOCK (VITEST)
// ============================================
test('action redirects on success', async () => {
const event = createMockEvent();
await expect(actions.login(event)).resolves.not.toThrow();
});
// ============================================
// PART 3: BROWSER TEST (PLAYWRIGHT)
// ============================================
test('navigation', async ({ page }) => {
await page.goto('/');
await page.click('text=About');
await expect(page).toHaveURL('/about');
});
This approach combines fast feedback loops for logic with high-confidence browser tests.
Quick Reference
Testing Approaches
| Tool | Strategy | Focus |
|---|---|---|
| Vitest | Unit/Integration | Pure logic, helper functions |
| Playwright | E2E | Browser flow, hydration, UI |
| MSW | API Mocking | Network layer (Fetch requests) |
Mocking Guide
| Item | Mocking Technique |
|---|---|
cookies | vi.fn() |
locals | Object literal |
params | Object literal |
fetch | vi.fn() or msw |
Best Practices
✅ Do This:
// Extract pure logic
export function processData(data: Data) { ... } // ✅
// Use factory for RequestEvent mocks
const event = createMockEvent({ locals: { user: {} } }); // ✅
// Test UI states in E2E
await expect(page.locator('.error')).toBeVisible(); // ✅
❌ Don’t Do This:
// Mocking the entire SvelteKit framework
// vi.mock('@sveltejs/kit') // Nightmare! // ❌
// Putting business logic inside load()
export const load = () => { /* 50 lines of logic */ } // ❌
// Relying on real APIs for unit tests
// await realDatabase.query() // Slow and flaky // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Flaky Tests | Real database dependency | Use MSW or Mock DB |
| Over-mocking | Trying to mock load | Factor out pure logic |
| Hydration Issues | Running components in Vitest | Use Playwright |
| Test Bloat | One test doing too much | Follow AAA pattern |
Real-World Examples
1. Testing a helper
expect(formatDate(new Date())).toBe('2023-01-01');
2. Mocking a cookie
event.cookies.get.mockReturnValue('token');
3. Playwright selector
await page.locator('button').click();
4. Checking URL state
await expect(page).toHaveURL(/dashboard/);
5. Mocking fetch
global.fetch = vi.fn().mockResolvedValue({ json: () => ({}) });
6. Form submission
await page.fill('input', 'value');
await page.press('Enter');
7. Asserting visibility
await expect(page.locator('.toast')).toBeHidden();
8. Stubbing locals
const event = { locals: { user: { id: 1 } } };
9. Testing actions
const result = await actions.update(event);
10. Snapshot Testing
expect(render(Component)).toMatchSnapshot();
Visual
The Testing Pyramid
┌──────────────────────────────────────────────┐
│ E2E (Playwright) ──► Real Browser │
│ Integration (Vitest + MSW) ──► Logic + Data │
│ Unit (Vitest) ──► Pure Functions │
└──────────────────────────────────────────────┘
The Request Mock Flow
┌──────────────────────────────────────────────┐
│ Test Case ──► Mock RequestEvent ──► Action │
│ │
│ Decouples test from framework runtime. │
└──────────────────────────────────────────────┘
AAA Pattern (Arrange-Act-Assert)
┌──────────────────────────────────────────────┐
│ Arrange: Setup mocks and inputs │
│ Act: Execute the function/action │
│ Assert: Verify the result/redirect │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Vitest | Fast, logic-focused |
| Playwright | Browser, integration-focused |
| Mocking | RequestEvent factories |
| Strategy | Extract logic to $lib |
| Pattern | Arrange-Act-Assert |
Key takeaways:
- Extract logic. The best way to test SvelteKit code is to keep
loadandactionsthin by moving business logic into pure functions. - Factory mocks are better than global mocks. Creating a
createMockEventhelper is more flexible and maintainable than trying to mock the SvelteKit framework globally. - E2E is for the user journey. Don’t test component rendering details in E2E; test that the user can login, navigate, and perform actions.
- Use MSW for network. When testing server logic that calls APIs, use Mock Service Worker (MSW) to intercept and mock the network responses.
- AAA pattern. Every test should follow the Arrange, Act, Assert pattern to ensure readability and simplify debugging when tests fail.
Remember: Tests are not just about finding bugs—they are documentation for how your application is expected to behave. By keeping your business logic pure and testing your framework integrations with tools like Playwright, you build a safety net that allows you to refactor and grow your SvelteKit application with confidence.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!