Files
pdnode-account/test-api.js
2025-07-29 15:36:25 -07:00

100 lines
3.0 KiB
JavaScript

const axios = require('axios');
const BASE_URL = 'http://localhost:3000/api/auth';
// 测试数据
const testUser = {
username: 'testuser',
email: 'test@example.com',
password: 'Password123'
};
let authToken = '';
// 测试函数
async function testAPI() {
console.log('🚀 开始测试API...\n');
try {
// 1. 测试注册
console.log('1. 测试用户注册...');
const registerResponse = await axios.post(`${BASE_URL}/register`, testUser);
console.log('✅ 注册成功:', registerResponse.data.message);
authToken = registerResponse.data.data.token;
console.log('Token:', authToken.substring(0, 20) + '...\n');
// 2. 测试重复注册(应该失败)
console.log('2. 测试重复注册...');
try {
await axios.post(`${BASE_URL}/register`, testUser);
} catch (error) {
console.log('✅ 重复注册被正确拒绝:', error.response.data.message);
}
console.log('');
// 3. 测试登录
console.log('3. 测试用户登录...');
const loginResponse = await axios.post(`${BASE_URL}/login`, {
username: testUser.username,
password: testUser.password
});
console.log('✅ 登录成功:', loginResponse.data.message);
console.log('');
// 4. 测试邮箱登录
console.log('4. 测试邮箱登录...');
const emailLoginResponse = await axios.post(`${BASE_URL}/login`, {
username: testUser.email,
password: testUser.password
});
console.log('✅ 邮箱登录成功:', emailLoginResponse.data.message);
console.log('');
// 5. 测试获取用户信息
console.log('5. 测试获取用户信息...');
const profileResponse = await axios.get(`${BASE_URL}/profile`, {
headers: {
'Authorization': `Bearer ${authToken}`
}
});
console.log('✅ 获取用户信息成功:', profileResponse.data.data.user.username);
console.log('');
// 6. 测试认证中间件
console.log('6. 测试认证中间件...');
const testResponse = await axios.get(`${BASE_URL}/test`, {
headers: {
'Authorization': `Bearer ${authToken}`
}
});
console.log('✅ 认证中间件测试成功:', testResponse.data.message);
console.log('');
// 7. 测试无效token
console.log('7. 测试无效token...');
try {
await axios.get(`${BASE_URL}/profile`, {
headers: {
'Authorization': 'Bearer invalid_token'
}
});
} catch (error) {
console.log('✅ 无效token被正确拒绝:', error.response.data.message);
}
console.log('');
// 8. 测试服务器状态
console.log('8. 测试服务器状态...');
const healthResponse = await axios.get('http://localhost:3000/health');
console.log('✅ 服务器状态正常:', healthResponse.data.message);
console.log('');
console.log('🎉 所有测试通过!');
} catch (error) {
console.error('❌ 测试失败:', error.response?.data || error.message);
}
}
// 运行测试
testAPI();