Files
gerenjizhang/test-api-full.js
T

228 lines
6.7 KiB
JavaScript

// API Integration Test Script
const BASE_URL = 'http://localhost:3001';
// Helper function for making requests
async function request(endpoint, options = {}) {
const url = `${BASE_URL}${endpoint}`;
const config = {
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
};
try {
const response = await fetch(url, config);
const data = await response.json();
return { status: response.status, ok: response.ok, data };
} catch (error) {
return { status: 500, ok: false, error: error.message };
}
}
// Test Results
const testResults = [];
async function runTests() {
console.log('🚀 Starting API Integration Tests...\n');
// 1. Health Check
console.log('1. Testing Health Check...');
const healthTest = await request('/health');
testResults.push({
name: 'Health Check',
passed: healthTest.ok,
status: healthTest.status,
data: healthTest.data
});
console.log(` ${healthTest.ok ? '✅' : '❌'} ${healthTest.status}`);
// 2. Create Test User
console.log('\n2. Testing Create User...');
const userTest = await request('/api/users', {
method: 'POST',
body: JSON.stringify({ name: 'Test User', email: 'test' + Date.now() + '@example.com' })
});
testResults.push({
name: 'Create User',
passed: userTest.ok,
status: userTest.status,
data: userTest.data
});
console.log(` ${userTest.ok ? '✅' : '❌'} ${userTest.status}`);
const userId = userTest.data?.data?.id;
if (!userId) {
console.log(' ❌ Cannot continue without user ID');
return;
}
console.log(` Created User ID: ${userId}`);
// 3. Create Account
console.log('\n3. Testing Create Account...');
const accountTest = await request('/api/accounts', {
method: 'POST',
body: JSON.stringify({ userId, name: '现金账户', type: 'cash', color: '#1890FF', balance: 1000 })
});
testResults.push({
name: 'Create Account',
passed: accountTest.ok,
status: accountTest.status,
data: accountTest.data
});
console.log(` ${accountTest.ok ? '✅' : '❌'} ${accountTest.status}`);
const accountId = accountTest.data?.data?.id;
// 4. Get Accounts
console.log('\n4. Testing Get Accounts...');
const getAccountsTest = await request(`/api/accounts?userId=${userId}`);
testResults.push({
name: 'Get Accounts',
passed: getAccountsTest.ok,
status: getAccountsTest.status,
data: getAccountsTest.data
});
console.log(` ${getAccountsTest.ok ? '✅' : '❌'} ${getAccountsTest.status}`);
// 5. Create Income Record
console.log('\n5. Testing Create Income Record...');
const incomeTest = await request('/api/records', {
method: 'POST',
body: JSON.stringify({
userId,
accountId,
type: 'income',
amount: 5000,
category: '工资',
description: '4月份工资',
date: new Date().toISOString()
})
});
testResults.push({
name: 'Create Income Record',
passed: incomeTest.ok,
status: incomeTest.status,
data: incomeTest.data
});
console.log(` ${incomeTest.ok ? '✅' : '❌'} ${incomeTest.status}`);
// 6. Create Expense Record
console.log('\n6. Testing Create Expense Record...');
const expenseTest = await request('/api/records', {
method: 'POST',
body: JSON.stringify({
userId,
accountId,
type: 'expense',
amount: 150,
category: '餐饮',
description: '午餐',
date: new Date().toISOString()
})
});
testResults.push({
name: 'Create Expense Record',
passed: expenseTest.ok,
status: expenseTest.status,
data: expenseTest.data
});
console.log(` ${expenseTest.ok ? '✅' : '❌'} ${expenseTest.status}`);
// 7. Get Records
console.log('\n7. Testing Get Records...');
const getRecordsTest = await request(`/api/records?userId=${userId}`);
testResults.push({
name: 'Get Records',
passed: getRecordsTest.ok,
status: getRecordsTest.status,
data: getRecordsTest.data
});
console.log(` ${getRecordsTest.ok ? '✅' : '❌'} ${getRecordsTest.status}`);
// 8. Create Budget
const currentMonth = `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`;
console.log('\n8. Testing Create Budget...');
const budgetTest = await request('/api/budgets', {
method: 'POST',
body: JSON.stringify({
userId,
category: '餐饮',
amount: 2000,
month: currentMonth
})
});
testResults.push({
name: 'Create Budget',
passed: budgetTest.ok,
status: budgetTest.status,
data: budgetTest.data
});
console.log(` ${budgetTest.ok ? '✅' : '❌'} ${budgetTest.status}`);
// 9. Get Budgets
console.log('\n9. Testing Get Budgets...');
const getBudgetsTest = await request(`/api/budgets?userId=${userId}&month=${currentMonth}`);
testResults.push({
name: 'Get Budgets',
passed: getBudgetsTest.ok,
status: getBudgetsTest.status,
data: getBudgetsTest.data
});
console.log(` ${getBudgetsTest.ok ? '✅' : '❌'} ${getBudgetsTest.status}`);
// 10. Monthly Statistics
console.log('\n10. Testing Monthly Statistics...');
const monthlyStatsTest = await request(`/api/statistics/monthly?userId=${userId}&month=${currentMonth}`);
testResults.push({
name: 'Monthly Statistics',
passed: monthlyStatsTest.ok,
status: monthlyStatsTest.status,
data: monthlyStatsTest.data
});
console.log(` ${monthlyStatsTest.ok ? '✅' : '❌'} ${monthlyStatsTest.status}`);
// 11. Trend Statistics
console.log('\n11. Testing Trend Statistics...');
const trendTest = await request(`/api/statistics/trend?userId=${userId}`);
testResults.push({
name: 'Trend Statistics',
passed: trendTest.ok,
status: trendTest.status,
data: trendTest.data
});
console.log(` ${trendTest.ok ? '✅' : '❌'} ${trendTest.status}`);
// 12. Dashboard Summary
console.log('\n12. Testing Dashboard Summary...');
const dashboardTest = await request(`/api/dashboard/summary?userId=${userId}`);
testResults.push({
name: 'Dashboard Summary',
passed: dashboardTest.ok,
status: dashboardTest.status,
data: dashboardTest.data
});
console.log(` ${dashboardTest.ok ? '✅' : '❌'} ${dashboardTest.status}`);
// Summary
console.log('\n' + '='.repeat(50));
console.log('📊 Test Summary:');
const passed = testResults.filter(t => t.passed).length;
const total = testResults.length;
console.log(` Total: ${total}`);
console.log(` Passed: ${passed}`);
console.log(` Failed: ${total - passed}`);
console.log('='.repeat(50));
return testResults;
}
runTests().then(results => {
console.log('\nTest run completed!');
process.exit(0);
}).catch(error => {
console.error('Test run failed:', error);
process.exit(1);
});