qapinterface
Version:
Comprehensive API utilities for Node.js applications including authentication, security, request processing, and response handling with zero external dependencies
181 lines (148 loc) • 5.36 kB
JavaScript
/**
* API Call Handler Test
* Tests the API call handling functionality
*/
const { handleApiCall } = require('../api/call-handler');
const { processApiResponse } = require('../api/response-processor');
const { extractApiError } = require('../api/error-extractor');
const { logApiCallStart, logApiCallSuccess, logApiCallError } = require('../api/call-logger');
// Test successful API call
async function testSuccessfulApiCall() {
console.log('\n=== Testing Successful API Call ===');
try {
// Mock successful API call
const mockApiCall = async () => ({
data: { message: 'Success', id: 123 }
});
const result = await handleApiCall(mockApiCall, 'testFunction', 'arg1', 'arg2');
console.log('✓ Successful API call result:', result);
console.log('✓ Should have message and id:', !!result.message && !!result.id);
return true;
} catch (error) {
console.error('✗ Successful API call test failed:', error);
return false;
}
}
// Test API call with error
async function testApiCallError() {
console.log('\n=== Testing API Call Error ===');
try {
// Mock failing API call
const mockApiCall = async () => {
const error = new Error('Network timeout');
error.response = {
status: 408,
data: { message: 'Request timeout' }
};
throw error;
};
await handleApiCall(mockApiCall, 'testErrorFunction', 'arg1');
console.error('✗ Should have thrown an error');
return false;
} catch (error) {
console.log('✓ Error caught successfully');
console.log('✓ Error has message:', !!error.message);
console.log('✓ Error has status:', !!error.status);
console.log('✓ Error has functionName:', !!error.functionName);
console.log('✓ Error details:', {
message: error.message,
status: error.status,
functionName: error.functionName
});
return true;
}
}
// Test response processing
function testResponseProcessing() {
console.log('\n=== Testing Response Processing ===');
try {
// Test axios-style response
const axiosResponse = { data: { result: 'success' } };
const processed1 = processApiResponse(axiosResponse, 'testAxios');
console.log('✓ Axios response processed:', processed1);
// Test direct data response
const directResponse = { result: 'direct' };
const processed2 = processApiResponse(directResponse, 'testDirect');
console.log('✓ Direct response processed:', processed2);
// Test primitive response
const primitiveResponse = 'simple string';
const processed3 = processApiResponse(primitiveResponse, 'testPrimitive');
console.log('✓ Primitive response processed:', processed3);
return true;
} catch (error) {
console.error('✗ Response processing test failed:', error);
return false;
}
}
// Test error extraction
function testErrorExtraction() {
console.log('\n=== Testing Error Extraction ===');
try {
// Test axios-style error
const axiosError = {
response: {
status: 400,
data: { message: 'Bad request' }
}
};
const extracted1 = extractApiError(axiosError, 'testFunction', ['arg1']);
console.log('✓ Axios error extracted:', extracted1);
// Test simple error
const simpleError = new Error('Simple error message');
const extracted2 = extractApiError(simpleError, 'testFunction2');
console.log('✓ Simple error extracted:', extracted2);
// Test network error
const networkError = { code: 'ECONNREFUSED' };
const extracted3 = extractApiError(networkError, 'testFunction3');
console.log('✓ Network error extracted (should be 503):', extracted3);
return true;
} catch (error) {
console.error('✗ Error extraction test failed:', error);
return false;
}
}
// Test logging functions
function testLogging() {
console.log('\n=== Testing API Call Logging ===');
try {
console.log('Testing logApiCallStart:');
logApiCallStart('testFunction', 'arg1', { key: 'value' });
console.log('Testing logApiCallSuccess:');
logApiCallSuccess('testFunction', { result: 'success' });
console.log('Testing logApiCallError:');
logApiCallError('testFunction', new Error('Test error'));
console.log('✓ All logging functions work correctly');
return true;
} catch (error) {
console.error('✗ Logging test failed:', error);
return false;
}
}
// Run all tests
async function runApiCallHandlerTests() {
console.log('🧪 API Call Handler Tests Starting...');
const results = await Promise.all([
testSuccessfulApiCall(),
testApiCallError(),
Promise.resolve(testResponseProcessing()),
Promise.resolve(testErrorExtraction()),
Promise.resolve(testLogging())
]);
const passed = results.filter(Boolean).length;
const total = results.length;
console.log(`\n📊 API Call Handler Tests: ${passed}/${total} passed`);
if (passed === total) {
console.log('✅ All API call handler tests passed!');
} else {
console.log('❌ Some API call handler tests failed');
}
return passed === total;
}
module.exports = {
runApiCallHandlerTests,
testSuccessfulApiCall,
testApiCallError,
testResponseProcessing,
testErrorExtraction,
testLogging
};