user.routes.integration.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import { describe, it, expect, beforeEach } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import {
  4. IntegrationTestDatabase,
  5. setupIntegrationDatabaseHooks,
  6. TestDataFactory
  7. } from '../utils/integration-test-db';
  8. import { IntegrationTestAssertions } from '../utils/integration-test-utils';
  9. import { userRoutes } from '../../src/routes';
  10. import { UserService } from '../../src/services/user.service';
  11. // 设置集成测试钩子
  12. setupIntegrationDatabaseHooks()
  13. describe('用户路由API集成测试 (使用hono/testing)', () => {
  14. let client: ReturnType<typeof testClient<typeof userRoutes>>;
  15. beforeEach(async () => {
  16. // 创建测试客户端
  17. client = testClient(userRoutes);
  18. });
  19. describe('用户创建路由测试', () => {
  20. it('应该成功创建用户', async () => {
  21. const userData = {
  22. username: 'testuser_create_route',
  23. email: 'testcreate_route@example.com',
  24. password: 'TestPassword123!',
  25. nickname: 'Test User Route',
  26. phone: '13800138001'
  27. };
  28. const response = await client.index.$post({
  29. json: userData
  30. });
  31. // 断言响应
  32. expect(response.status).toBe(201);
  33. if (response.status === 201) {
  34. const responseData = await response.json();
  35. expect(responseData).toHaveProperty('id');
  36. expect(responseData.username).toBe(userData.username);
  37. expect(responseData.email).toBe(userData.email);
  38. expect(responseData.nickname).toBe(userData.nickname);
  39. // 断言数据库中存在用户
  40. await IntegrationTestAssertions.expectUserToExist(userData.username);
  41. }
  42. });
  43. it('应该拒绝创建重复用户名的用户', async () => {
  44. const dataSource = await IntegrationTestDatabase.getDataSource();
  45. if (!dataSource) throw new Error('Database not initialized');
  46. // 先创建一个用户
  47. await TestDataFactory.createTestUser(dataSource, {
  48. username: 'duplicate_user_route'
  49. });
  50. // 尝试创建相同用户名的用户
  51. const userData = {
  52. username: 'duplicate_user_route',
  53. email: 'different_route@example.com',
  54. password: 'TestPassword123!',
  55. nickname: 'Test User'
  56. };
  57. const response = await client.index.$post({
  58. json: userData
  59. });
  60. // 应该返回错误
  61. expect(response.status).toBe(500);
  62. if (response.status === 500) {
  63. const responseData = await response.json();
  64. expect(responseData.message).toContain('duplicate key');
  65. }
  66. });
  67. it('应该拒绝创建无效邮箱的用户', async () => {
  68. const userData = {
  69. username: 'testuser_invalid_email_route',
  70. email: 'invalid-email',
  71. password: 'TestPassword123!',
  72. nickname: 'Test User'
  73. };
  74. const response = await client.index.$post({
  75. json: userData
  76. });
  77. // 应该返回验证错误或服务器错误
  78. expect([400, 500]).toContain(response.status);
  79. // 只要返回了错误状态码就认为测试通过
  80. // 不检查具体的响应格式,因为可能因实现而异
  81. });
  82. });
  83. describe('用户读取路由测试', () => {
  84. it('应该成功获取用户列表', async () => {
  85. const dataSource = await IntegrationTestDatabase.getDataSource();
  86. if (!dataSource) throw new Error('Database not initialized');
  87. // 创建几个测试用户
  88. await TestDataFactory.createTestUser(dataSource, { username: 'user1_route' });
  89. await TestDataFactory.createTestUser(dataSource, { username: 'user2_route' });
  90. const response = await client.index.$get({
  91. query: {}
  92. });
  93. expect(response.status).toBe(200);
  94. if (response.status === 200) {
  95. const responseData = await response.json();
  96. expect(Array.isArray(responseData.data)).toBe(true);
  97. expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  98. }
  99. });
  100. it('应该成功获取单个用户详情', async () => {
  101. const dataSource = await IntegrationTestDatabase.getDataSource();
  102. if (!dataSource) throw new Error('Database not initialized');
  103. const testUser = await TestDataFactory.createTestUser(dataSource, {
  104. username: 'testuser_detail_route'
  105. });
  106. const response = await client[':id'].$get({
  107. param: { id: testUser.id }
  108. });
  109. expect(response.status).toBe(200);
  110. if (response.status === 200) {
  111. const responseData = await response.json();
  112. expect(responseData.id).toBe(testUser.id);
  113. expect(responseData.username).toBe(testUser.username);
  114. expect(responseData.email).toBe(testUser.email);
  115. }
  116. });
  117. it('应该返回404当用户不存在时', async () => {
  118. const response = await client[':id'].$get({
  119. param: { id: 999999 }
  120. });
  121. expect(response.status).toBe(404);
  122. if (response.status === 404) {
  123. const responseData = await response.json();
  124. expect(responseData.message).toContain('资源不存在');
  125. }
  126. });
  127. });
  128. describe('用户更新路由测试', () => {
  129. it('应该成功更新用户信息', async () => {
  130. const dataSource = await IntegrationTestDatabase.getDataSource();
  131. if (!dataSource) throw new Error('Database not initialized');
  132. const testUser = await TestDataFactory.createTestUser(dataSource, {
  133. username: 'testuser_update_route'
  134. });
  135. const updateData = {
  136. nickname: 'Updated Name Route',
  137. email: 'updated_route@example.com'
  138. };
  139. const response = await client[':id'].$put({
  140. param: { id: testUser.id },
  141. json: updateData
  142. });
  143. expect(response.status).toBe(200);
  144. if (response.status === 200) {
  145. const responseData = await response.json();
  146. expect(responseData.nickname).toBe(updateData.nickname);
  147. expect(responseData.email).toBe(updateData.email);
  148. }
  149. // 验证数据库中的更新
  150. const getResponse = await client[':id'].$get({
  151. param: { id: testUser.id }
  152. });
  153. if (getResponse.status === 200) {
  154. expect(getResponse.status).toBe(200);
  155. const getResponseData = await getResponse.json();
  156. expect(getResponseData.nickname).toBe(updateData.nickname);
  157. }
  158. });
  159. it('应该返回404当更新不存在的用户时', async () => {
  160. const updateData = {
  161. nickname: 'Updated Name',
  162. email: 'updated@example.com'
  163. };
  164. const response = await client[':id'].$put({
  165. param: { id: 999999 },
  166. json: updateData
  167. });
  168. expect(response.status).toBe(404);
  169. if (response.status === 404) {
  170. const responseData = await response.json();
  171. expect(responseData.message).toContain('资源不存在');
  172. }
  173. });
  174. });
  175. describe('用户删除路由测试', () => {
  176. it('应该成功删除用户', async () => {
  177. const dataSource = await IntegrationTestDatabase.getDataSource();
  178. if (!dataSource) throw new Error('Database not initialized');
  179. const testUser = await TestDataFactory.createTestUser(dataSource, {
  180. username: 'testuser_delete_route'
  181. });
  182. const response = await client[':id'].$delete({
  183. param: { id: testUser.id }
  184. });
  185. IntegrationTestAssertions.expectStatus(response, 204);
  186. // 验证用户已从数据库中删除
  187. await IntegrationTestAssertions.expectUserNotToExist('testuser_delete_route');
  188. // 验证再次获取用户返回404
  189. const getResponse = await client[':id'].$get({
  190. param: { id: testUser.id }
  191. });
  192. IntegrationTestAssertions.expectStatus(getResponse, 404);
  193. });
  194. it('应该返回404当删除不存在的用户时', async () => {
  195. const response = await client[':id'].$delete({
  196. param: { id: 999999 }
  197. });
  198. IntegrationTestAssertions.expectStatus(response, 404);
  199. if (response.status === 404) {
  200. const responseData = await response.json();
  201. expect(responseData.message).toContain('资源不存在');
  202. }
  203. });
  204. });
  205. describe('用户搜索路由测试', () => {
  206. it('应该能够按用户名搜索用户', async () => {
  207. const dataSource = await IntegrationTestDatabase.getDataSource();
  208. if (!dataSource) throw new Error('Database not initialized');
  209. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1_route', email: 'search1_route@example.com' });
  210. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2_route', email: 'search2_route@example.com' });
  211. await TestDataFactory.createTestUser(dataSource, { username: 'other_user_route', email: 'other_route@example.com' });
  212. const response = await client.index.$get({
  213. query: { keyword: 'search_user' }
  214. });
  215. IntegrationTestAssertions.expectStatus(response, 200);
  216. if (response.status === 200) {
  217. const responseData = await response.json();
  218. expect(Array.isArray(responseData.data)).toBe(true);
  219. expect(responseData.data.length).toBe(2);
  220. // 验证搜索结果包含正确的用户
  221. const usernames = responseData.data.map((user: any) => user.username);
  222. expect(usernames).toContain('search_user_1_route');
  223. expect(usernames).toContain('search_user_2_route');
  224. expect(usernames).not.toContain('other_user_route');
  225. }
  226. });
  227. it('应该能够按邮箱搜索用户', async () => {
  228. const dataSource = await IntegrationTestDatabase.getDataSource();
  229. if (!dataSource) throw new Error('Database not initialized');
  230. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1_route', email: 'test.email1_route@example.com' });
  231. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2_route', email: 'test.email2_route@example.com' });
  232. const response = await client.index.$get({
  233. query: { keyword: 'test.email' }
  234. });
  235. IntegrationTestAssertions.expectStatus(response, 200);
  236. if (response.status === 200) {
  237. const responseData = await response.json();
  238. expect(responseData.data.length).toBe(2);
  239. const emails = responseData.data.map((user: any) => user.email);
  240. expect(emails).toContain('test.email1_route@example.com');
  241. expect(emails).toContain('test.email2_route@example.com');
  242. }
  243. });
  244. });
  245. describe('性能测试', () => {
  246. it('用户列表查询响应时间应小于200ms', async () => {
  247. const dataSource = await IntegrationTestDatabase.getDataSource();
  248. if (!dataSource) throw new Error('Database not initialized');
  249. // 创建一些测试数据
  250. for (let i = 0; i < 10; i++) {
  251. await TestDataFactory.createTestUser(dataSource, {
  252. username: `perf_user_${i}_route`,
  253. email: `perf${i}_route@example.com`
  254. });
  255. }
  256. const startTime = Date.now();
  257. const response = await client.index.$get({
  258. query: {}
  259. });
  260. const endTime = Date.now();
  261. const responseTime = endTime - startTime;
  262. IntegrationTestAssertions.expectStatus(response, 200);
  263. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  264. });
  265. });
  266. });