user.routes.integration.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. if (response.status === 400) {
  80. const responseData = await response.json();
  81. // 检查是否有code属性,如果没有则检查message
  82. if (responseData.code !== undefined) {
  83. expect(responseData.code).toBe(400);
  84. } else {
  85. expect(responseData.message).toBeDefined();
  86. }
  87. } else if (response.status === 500) {
  88. const responseData = await response.json();
  89. expect(responseData.message).toBeDefined();
  90. }
  91. });
  92. });
  93. describe('用户读取路由测试', () => {
  94. it('应该成功获取用户列表', async () => {
  95. const dataSource = await IntegrationTestDatabase.getDataSource();
  96. if (!dataSource) throw new Error('Database not initialized');
  97. // 创建几个测试用户
  98. await TestDataFactory.createTestUser(dataSource, { username: 'user1_route' });
  99. await TestDataFactory.createTestUser(dataSource, { username: 'user2_route' });
  100. const response = await client.index.$get({
  101. query: {}
  102. });
  103. expect(response.status).toBe(200);
  104. if (response.status === 200) {
  105. const responseData = await response.json();
  106. expect(Array.isArray(responseData.data)).toBe(true);
  107. expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  108. }
  109. });
  110. it('应该成功获取单个用户详情', async () => {
  111. const dataSource = await IntegrationTestDatabase.getDataSource();
  112. if (!dataSource) throw new Error('Database not initialized');
  113. const testUser = await TestDataFactory.createTestUser(dataSource, {
  114. username: 'testuser_detail_route'
  115. });
  116. const response = await client[':id'].$get({
  117. param: { id: testUser.id }
  118. });
  119. expect(response.status).toBe(200);
  120. if (response.status === 200) {
  121. const responseData = await response.json();
  122. expect(responseData.id).toBe(testUser.id);
  123. expect(responseData.username).toBe(testUser.username);
  124. expect(responseData.email).toBe(testUser.email);
  125. }
  126. });
  127. it('应该返回404当用户不存在时', async () => {
  128. const response = await client[':id'].$get({
  129. param: { id: 999999 }
  130. });
  131. expect(response.status).toBe(404);
  132. if (response.status === 404) {
  133. const responseData = await response.json();
  134. expect(responseData.message).toContain('资源不存在');
  135. }
  136. });
  137. });
  138. describe('用户更新路由测试', () => {
  139. it('应该成功更新用户信息', async () => {
  140. const dataSource = await IntegrationTestDatabase.getDataSource();
  141. if (!dataSource) throw new Error('Database not initialized');
  142. const testUser = await TestDataFactory.createTestUser(dataSource, {
  143. username: 'testuser_update_route'
  144. });
  145. const updateData = {
  146. nickname: 'Updated Name Route',
  147. email: 'updated_route@example.com'
  148. };
  149. const response = await client[':id'].$put({
  150. param: { id: testUser.id },
  151. json: updateData
  152. });
  153. expect(response.status).toBe(200);
  154. if (response.status === 200) {
  155. const responseData = await response.json();
  156. expect(responseData.nickname).toBe(updateData.nickname);
  157. expect(responseData.email).toBe(updateData.email);
  158. }
  159. // 验证数据库中的更新
  160. const getResponse = await client[':id'].$get({
  161. param: { id: testUser.id }
  162. });
  163. if (getResponse.status === 200) {
  164. expect(getResponse.status).toBe(200);
  165. const getResponseData = await getResponse.json();
  166. expect(getResponseData.nickname).toBe(updateData.nickname);
  167. }
  168. });
  169. it('应该返回404当更新不存在的用户时', async () => {
  170. const updateData = {
  171. nickname: 'Updated Name',
  172. email: 'updated@example.com'
  173. };
  174. const response = await client[':id'].$put({
  175. param: { id: 999999 },
  176. json: updateData
  177. });
  178. expect(response.status).toBe(404);
  179. if (response.status === 404) {
  180. const responseData = await response.json();
  181. expect(responseData.message).toContain('资源不存在');
  182. }
  183. });
  184. });
  185. describe('用户删除路由测试', () => {
  186. it('应该成功删除用户', async () => {
  187. const dataSource = await IntegrationTestDatabase.getDataSource();
  188. if (!dataSource) throw new Error('Database not initialized');
  189. const testUser = await TestDataFactory.createTestUser(dataSource, {
  190. username: 'testuser_delete_route'
  191. });
  192. const response = await client[':id'].$delete({
  193. param: { id: testUser.id }
  194. });
  195. IntegrationTestAssertions.expectStatus(response, 204);
  196. // 验证用户已从数据库中删除
  197. await IntegrationTestAssertions.expectUserNotToExist('testuser_delete_route');
  198. // 验证再次获取用户返回404
  199. const getResponse = await client[':id'].$get({
  200. param: { id: testUser.id }
  201. });
  202. IntegrationTestAssertions.expectStatus(getResponse, 404);
  203. });
  204. it('应该返回404当删除不存在的用户时', async () => {
  205. const response = await client[':id'].$delete({
  206. param: { id: 999999 }
  207. });
  208. IntegrationTestAssertions.expectStatus(response, 404);
  209. if (response.status === 404) {
  210. const responseData = await response.json();
  211. expect(responseData.message).toContain('资源不存在');
  212. }
  213. });
  214. });
  215. describe('用户搜索路由测试', () => {
  216. it('应该能够按用户名搜索用户', async () => {
  217. const dataSource = await IntegrationTestDatabase.getDataSource();
  218. if (!dataSource) throw new Error('Database not initialized');
  219. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1_route', email: 'search1_route@example.com' });
  220. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2_route', email: 'search2_route@example.com' });
  221. await TestDataFactory.createTestUser(dataSource, { username: 'other_user_route', email: 'other_route@example.com' });
  222. const response = await client.index.$get({
  223. query: { keyword: 'search_user' }
  224. });
  225. IntegrationTestAssertions.expectStatus(response, 200);
  226. if (response.status === 200) {
  227. const responseData = await response.json();
  228. expect(Array.isArray(responseData.data)).toBe(true);
  229. expect(responseData.data.length).toBe(2);
  230. // 验证搜索结果包含正确的用户
  231. const usernames = responseData.data.map((user: any) => user.username);
  232. expect(usernames).toContain('search_user_1_route');
  233. expect(usernames).toContain('search_user_2_route');
  234. expect(usernames).not.toContain('other_user_route');
  235. }
  236. });
  237. it('应该能够按邮箱搜索用户', async () => {
  238. const dataSource = await IntegrationTestDatabase.getDataSource();
  239. if (!dataSource) throw new Error('Database not initialized');
  240. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1_route', email: 'test.email1_route@example.com' });
  241. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2_route', email: 'test.email2_route@example.com' });
  242. const response = await client.index.$get({
  243. query: { keyword: 'test.email' }
  244. });
  245. IntegrationTestAssertions.expectStatus(response, 200);
  246. if (response.status === 200) {
  247. const responseData = await response.json();
  248. expect(responseData.data.length).toBe(2);
  249. const emails = responseData.data.map((user: any) => user.email);
  250. expect(emails).toContain('test.email1_route@example.com');
  251. expect(emails).toContain('test.email2_route@example.com');
  252. }
  253. });
  254. });
  255. describe('性能测试', () => {
  256. it('用户列表查询响应时间应小于200ms', async () => {
  257. const dataSource = await IntegrationTestDatabase.getDataSource();
  258. if (!dataSource) throw new Error('Database not initialized');
  259. // 创建一些测试数据
  260. for (let i = 0; i < 10; i++) {
  261. await TestDataFactory.createTestUser(dataSource, {
  262. username: `perf_user_${i}_route`,
  263. email: `perf${i}_route@example.com`
  264. });
  265. }
  266. const startTime = Date.now();
  267. const response = await client.index.$get({
  268. query: {}
  269. });
  270. const endTime = Date.now();
  271. const responseTime = endTime - startTime;
  272. IntegrationTestAssertions.expectStatus(response, 200);
  273. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  274. });
  275. });
  276. });