2
0

integration-test-utils.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { IntegrationTestDatabase } from './integration-test-db';
  2. import { UserEntity } from '@d8d/server/modules/users/user.entity';
  3. /**
  4. * 集成测试断言工具
  5. */
  6. export class IntegrationTestAssertions {
  7. /**
  8. * 断言响应状态码
  9. */
  10. static expectStatus(response: { status: number }, expectedStatus: number): void {
  11. if (response.status !== expectedStatus) {
  12. throw new Error(`Expected status ${expectedStatus}, but got ${response.status}`);
  13. }
  14. }
  15. /**
  16. * 断言响应包含特定字段
  17. */
  18. static expectResponseToHave(response: { data: any }, expectedFields: Record<string, any>): void {
  19. for (const [key, value] of Object.entries(expectedFields)) {
  20. if (response.data[key] !== value) {
  21. throw new Error(`Expected field ${key} to be ${value}, but got ${response.data[key]}`);
  22. }
  23. }
  24. }
  25. /**
  26. * 断言响应包含特定结构
  27. */
  28. static expectResponseStructure(response: { data: any }, structure: Record<string, any>): void {
  29. for (const key of Object.keys(structure)) {
  30. if (!(key in response.data)) {
  31. throw new Error(`Expected response to have key: ${key}`);
  32. }
  33. }
  34. }
  35. /**
  36. * 断言用户存在于数据库中
  37. */
  38. static async expectUserToExist(username: string): Promise<void> {
  39. const dataSource = await IntegrationTestDatabase.getDataSource();
  40. if (!dataSource) {
  41. throw new Error('Database not initialized');
  42. }
  43. const userRepository = dataSource.getRepository(UserEntity);
  44. const user = await userRepository.findOne({ where: { username } });
  45. if (!user) {
  46. throw new Error(`Expected user ${username} to exist in database`);
  47. }
  48. }
  49. /**
  50. * 断言用户不存在于数据库中
  51. */
  52. static async expectUserNotToExist(username: string): Promise<void> {
  53. const dataSource = await IntegrationTestDatabase.getDataSource();
  54. if (!dataSource) {
  55. throw new Error('Database not initialized');
  56. }
  57. const userRepository = dataSource.getRepository(UserEntity);
  58. const user = await userRepository.findOne({ where: { username } });
  59. if (user) {
  60. throw new Error(`Expected user ${username} not to exist in database`);
  61. }
  62. }
  63. }