/**
* 网络错误处理测试
*/
/// <reference path="../global.d.ts" />
import { ZenTaoClient } from '../../src/client';
describe('Network Error Handling', () => {
test('should handle connection timeout', async () => {
const slowClient = new ZenTaoClient({
baseUrl: 'http://localhost',
token: global.testConfig.token,
timeout: 100, // 很短的超时
retry: 1,
retryDelay: 100
}, global.testLogger);
await expect(slowClient.get('/api.php/v1/projects'))
.rejects
.toThrow();
console.log('✅ Connection timeout handled');
}, 5000);
test('should handle server unavailable', async () => {
const unavailableClient = new ZenTaoClient({
baseUrl: 'http://nonexistent-server-12345.com',
token: 'test_token',
timeout: 5000,
retry: 1
}, global.testLogger);
await expect(unavailableClient.verifyConnection())
.rejects
.toThrow();
console.log('✅ Server unavailable handled');
}, 10000);
test('should retry on temporary failures', async () => {
let attemptCount = 0;
const mockClient = new ZenTaoClient({
baseUrl: 'http://localhost',
token: global.testConfig.token,
timeout: 5000,
retry: 3,
retryDelay: 100
}, global.testLogger);
// 模拟前两次失败,第三次成功
const originalGet = mockClient.get.bind(mockClient);
mockClient.get = jest.fn().mockImplementation(async (...args: any[]) => {
attemptCount++;
if (attemptCount < 3) {
throw new Error('Temporary network error');
}
return originalGet(...args);
});
const result = await mockClient.get('/api.php/v1/projects');
expect(result).toBeDefined();
expect(attemptCount).toBe(3);
console.log(`✅ Retried ${attemptCount} times before success`);
});
test('should fail after max retries', async () => {
const failingClient = new ZenTaoClient({
baseUrl: 'http://localhost',
token: global.testConfig.token,
timeout: 5000,
retry: 2,
retryDelay: 100
}, global.testLogger);
// 始终失败
const originalGet = failingClient.get.bind(failingClient);
failingClient.get = jest.fn().mockRejectedValue(new Error('Always failing'));
await expect(failingClient.get('/api.php/v1/projects'))
.rejects
.toThrow();
console.log('✅ Failed after max retries');
});
});