official-provider.test.js•1.49 kB
import { describe, it, expect, beforeEach, vi } from 'vitest';
const mockFetchWithRetry = vi.fn();
vi.mock('../../src/providers/sharedFetch.js', () => ({
fetchWithRetry: mockFetchWithRetry,
}));
const { getJoke } = await import('../../src/providers/official.js');
describe('Official Joke API provider', () => {
beforeEach(() => {
mockFetchWithRetry.mockReset();
});
it('throws when non-English language requested', async () => {
await expect(
getJoke({ category: 'general', lang: 'zh', blacklist: [] }, { allowNet: true }),
).rejects.toThrow('Official Joke API only provides English jokes');
});
it('normalizes response into shared shape', async () => {
mockFetchWithRetry.mockResolvedValue(
new Response(
JSON.stringify({
type: 'programming',
setup: 'Why do functions always break up?',
punchline: 'Because they have arguments.',
}),
{ headers: { 'Content-Type': 'application/json' } },
),
);
const joke = await getJoke(
{ category: 'programming', lang: 'en', blacklist: [] },
{ allowNet: true, timeoutMs: 500, retries: 0 },
);
expect(joke.source).toBe('official');
expect(joke.category).toBe('programming');
expect(joke.text).toContain('arguments');
expect(mockFetchWithRetry).toHaveBeenCalledTimes(1);
const [requestedUrl] = mockFetchWithRetry.mock.calls[0];
expect(requestedUrl).toContain('/jokes/programming/random');
});
});