0 day streak
javascript / intermediate
Snippet

Mocking Async Network Requests in Svelte Component Tests

Components fetching data asynchronously require isolated network mocking during integration testing. Using Mock Service Worker (MSW) intercepts network-level HTTP requests and supplies deterministic JSON payloads, allowing tests to verify loading states and resolved UI states reliably.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { render, screen, waitFor } from '@testing-library/svelte';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import UserLoader from './UserLoader.svelte';
const server = setupServer(
http.get('/api/user', () => HttpResponse.json({ name: 'Alex', role: 'Developer' }))
);
beforeAll(() => server.listen());
afterAll(() => server.close());
test('fetches and displays user profile data', async () => {
render(UserLoader);
expect(screen.getByText('Loading...')).toBeTruthy();
await waitFor(() => {
expect(screen.getByText('Alex - Developer')).toBeTruthy();
});
});
svelte
Breakdown
1
const server = setupServer( http.get('/api/user', () => HttpResponse.json({ name: 'Alex', role: 'Developer' })) );
Configures a mock server instance to intercept matching HTTP GET requests and respond with fake JSON data.
2
render(UserLoader);
Mounts the target Svelte component, which immediately triggers its internal lifecycle network request.
3
await waitFor(() => { expect(screen.getByText('Alex - Developer')).toBeTruthy(); });
Repeatedly checks the DOM until the asynchronous network call finishes and the rendered text appears.