user.routes.integration.test.ts 11 KB

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