auth-flow.test.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * 认证流程集成测试
  3. * 测试注册→登录→Token刷新完整流程
  4. */
  5. import { describe, it, expect, beforeAll } from 'vitest';
  6. import { apiPost, apiGet, setAuthToken, initHttpClient } from '../../integration/http-client';
  7. const BASE_URL = 'http://localhost:3000';
  8. describe('认证流程集成测试', () => {
  9. let testPhone: string;
  10. let authToken: string;
  11. beforeAll(() => {
  12. initHttpClient();
  13. testPhone = `138${Date.now()}`.slice(0, 11);
  14. });
  15. describe('发送验证码', () => {
  16. it('发送验证码成功', async () => {
  17. const res = await apiPost('/api/auth/send-code', { phone: testPhone });
  18. expect(res.code).toBe(0);
  19. });
  20. it('无效手机号格式被拒绝', async () => {
  21. const res = await apiPost('/api/auth/send-code', { phone: '123' });
  22. expect(res.code).not.toBe(0);
  23. });
  24. });
  25. describe('登录/注册', () => {
  26. it('新用户注册并登录', async () => {
  27. await apiPost('/api/auth/send-code', { phone: testPhone });
  28. const res = await apiPost('/api/auth/login', {
  29. phone: testPhone,
  30. code: '123456'
  31. });
  32. expect(res.code).toBe(0);
  33. expect(res.data?.token).toBeDefined();
  34. authToken = res.data?.token;
  35. setAuthToken(authToken);
  36. });
  37. it('获取用户信息', async () => {
  38. const res = await apiGet('/api/auth/user-info');
  39. expect(res.code).toBe(0);
  40. expect(res.data?.phone).toBe(testPhone);
  41. });
  42. it('Token 无效时返回认证错误', async () => {
  43. setAuthToken('invalid_token_12345');
  44. const res = await apiGet('/api/auth/user-info');
  45. expect(res.code).not.toBe(0);
  46. });
  47. });
  48. describe('Token 刷新', () => {
  49. it('有效 Token 获取用户信息成功', async () => {
  50. if (!authToken) {
  51. await apiPost('/api/auth/send-code', { phone: testPhone });
  52. const loginRes = await apiPost('/api/auth/login', {
  53. phone: testPhone,
  54. code: '123456'
  55. });
  56. authToken = loginRes.data?.token || '';
  57. setAuthToken(authToken);
  58. }
  59. const res = await apiGet('/api/auth/user-info');
  60. expect(res.code).toBe(0);
  61. expect(res.data).toBeDefined();
  62. });
  63. });
  64. describe('会员状态', () => {
  65. it('新用户默认免费会员', async () => {
  66. if (!authToken) return;
  67. const res = await apiGet('/api/auth/user-info');
  68. expect(res.data?.memberLevel).toBe(0);
  69. });
  70. });
  71. });