Files
nxxmdata/backend/test-users-api.js
2025-08-25 15:00:46 +08:00

118 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 测试用户管理API
*/
const axios = require('axios');
const API_BASE_URL = 'http://localhost:5350/api';
// 测试用户登录并获取token
async function testLogin() {
try {
console.log('测试用户登录...');
const response = await axios.post(`${API_BASE_URL}/auth/login`, {
username: 'admin',
password: '123456'
});
if (response.data.success) {
console.log('✓ 登录成功');
console.log('Token:', response.data.token);
return response.data.token;
} else {
console.log('✗ 登录失败:', response.data.message);
return null;
}
} catch (error) {
console.log('✗ 登录请求失败:', error.message);
return null;
}
}
// 测试获取用户列表
async function testGetUsers(token) {
try {
console.log('\n测试获取用户列表...');
const response = await axios.get(`${API_BASE_URL}/users`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.data.success) {
console.log('✓ 获取用户列表成功');
console.log('用户数量:', response.data.data.length);
response.data.data.forEach(user => {
console.log(`- ${user.username} (${user.email}) - 角色: ${user.role}`);
});
return true;
} else {
console.log('✗ 获取用户列表失败:', response.data.message);
return false;
}
} catch (error) {
console.log('✗ 获取用户列表请求失败:', error.message);
return false;
}
}
// 测试创建用户
async function testCreateUser(token) {
try {
console.log('\n测试创建用户...');
const newUser = {
username: 'testuser_' + Date.now(),
email: `test_${Date.now()}@example.com`,
password: '123456',
role: 'user'
};
const response = await axios.post(`${API_BASE_URL}/users`, newUser, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.data.success) {
console.log('✓ 创建用户成功');
console.log('新用户ID:', response.data.data.id);
return response.data.data.id;
} else {
console.log('✗ 创建用户失败:', response.data.message);
return null;
}
} catch (error) {
console.log('✗ 创建用户请求失败:', error.response?.data?.message || error.message);
return null;
}
}
// 主测试函数
async function runTests() {
console.log('开始测试用户管理API...');
console.log('=' .repeat(50));
// 1. 测试登录
const token = await testLogin();
if (!token) {
console.log('\n测试终止无法获取认证token');
return;
}
// 2. 测试获取用户列表
await testGetUsers(token);
// 3. 测试创建用户
const newUserId = await testCreateUser(token);
// 4. 再次获取用户列表,验证新用户是否创建成功
if (newUserId) {
console.log('\n验证新用户是否创建成功...');
await testGetUsers(token);
}
console.log('\n测试完成!');
}
// 运行测试
runTests().catch(console.error);