Testing & Declarative Mock Adapter
Stub matching routes, simulate network errors, and inspect captured request history in your test runner.
Declarative Unit Testing with createMockAdapter
createMockAdapter replaces the client's Fetch implementation with route handlers for test requests:
api.test.ts
typescript
import { describe, it, expect, beforeEach } from 'vitest';
import { createClient, createMockAdapter } from 'react-native-fetch-client';
describe('User API Service', () => {
let api: any;
let mock: any;
beforeEach(() => {
api = createClient({ baseURL: 'https://api.test.com' });
mock = createMockAdapter(api);
});
it('fetches user successfully', async () => {
// 1. Stub a route
mock.onGet('/users/1').reply(200, { id: 1, name: 'Alice' });
// 2. Call your service
const res = await api.get('/users/1');
expect(res.status).toBe(200);
expect(res.data.name).toBe('Alice');
// 3. Assert call history
expect(mock.history.get.length).toBe(1);
expect(mock.history.get[0].url).toContain('/users/1');
});
it('handles network failure', async () => {
mock.onPost('/checkout').replyWithNetworkError('Simulated offline failure');
const [data, error] = await api.safe.post('/checkout', { amount: 100 });
expect(error).not.toBeNull();
expect(error?.message).toContain('Simulated offline failure');
});
});No mock server in this example
These examples use the package's adapter and do not start a local HTTP server. You can still use other mocking tools in your test setup if needed.