axios.mock.ts•2.93 kB
/**
* Mock implementation of axios for testing
* This prevents any real HTTP requests during tests
*/
import { jest } from '@jest/globals';
// Sample mock response data
const MOCK_TOP_NEWS_RESPONSE = {
meta: {
found: 2,
returned: 2,
limit: 10,
page: 1
},
data: [
{
uuid: 'test-uuid-1',
title: 'Test Article 1',
description: 'Test description 1',
url: 'https://example.com/article1',
image_url: 'https://example.com/image1.jpg',
published_at: new Date().toISOString(),
source: 'Test Source 1',
categories: ['general'],
language: 'en'
},
{
uuid: 'test-uuid-2',
title: 'Test Article 2',
description: 'Test description 2',
url: 'https://example.com/article2',
image_url: 'https://example.com/image2.jpg',
published_at: new Date().toISOString(),
source: 'Test Source 2',
categories: ['technology'],
language: 'en'
}
]
};
const MOCK_NEWS_BY_UUID = {
uuid: 'test-uuid-1',
title: 'Test Article 1',
description: 'Test description 1',
url: 'https://example.com/article1',
image_url: 'https://example.com/image1.jpg',
published_at: new Date().toISOString(),
source: 'Test Source 1',
categories: ['general'],
language: 'en'
};
const MOCK_SOURCES_RESPONSE = {
meta: {
found: 2,
returned: 2,
limit: 10,
page: 1
},
data: [
{
id: 1,
name: 'Test Source 1',
url: 'https://example.com/source1'
},
{
id: 2,
name: 'Test Source 2',
url: 'https://example.com/source2'
}
]
};
// Create mock axios implementation
const mockAxios = {
get: jest.fn().mockImplementation((url: string) => {
if (url.includes('/top')) {
return Promise.resolve({ data: MOCK_TOP_NEWS_RESPONSE });
} else if (url.includes('/all')) {
return Promise.resolve({ data: MOCK_TOP_NEWS_RESPONSE });
} else if (url.includes('/uuid/')) {
const uuidMatch = url.match(/\/uuid\/([^/?]+)/);
const uuid = uuidMatch ? uuidMatch[1] : null;
if (uuid === 'test-uuid-1') {
return Promise.resolve({ data: { data: MOCK_NEWS_BY_UUID } });
} else {
// Return 404 for non-existent UUIDs
const error: any = new Error('Article not found');
error.response = { status: 404 };
return Promise.reject(error);
}
} else if (url.includes('/sources')) {
return Promise.resolve({ data: MOCK_SOURCES_RESPONSE });
}
// Default fallback
return Promise.resolve({ data: { data: [] } });
}),
defaults: {
baseURL: 'https://api.example.com',
headers: {
common: {}
}
},
interceptors: {
request: {
use: jest.fn(),
eject: jest.fn()
},
response: {
use: jest.fn(),
eject: jest.fn()
}
}
};
// Mock axios module
jest.mock('axios', () => mockAxios);
export default mockAxios;