parseWithAwait.test.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import { describe, it, expect } from 'vitest';
  2. import { z } from '@hono/zod-openapi';
  3. import { parseWithAwait } from '../../src/utils/parseWithAwait';
  4. describe('parseWithAwait', () => {
  5. const testSchema = z.object({
  6. name: z.string(),
  7. age: z.number(),
  8. email: z.string().email()
  9. });
  10. it('应该成功解析同步数据', async () => {
  11. const data = {
  12. name: 'John Doe',
  13. age: 30,
  14. email: 'john@example.com'
  15. };
  16. const result = await parseWithAwait(testSchema, data);
  17. expect(result).toEqual(data);
  18. });
  19. it('应该成功解析包含Promise的数据', async () => {
  20. const data = {
  21. name: Promise.resolve('John Doe'),
  22. age: 30,
  23. email: 'john@example.com'
  24. };
  25. const result = await parseWithAwait(testSchema, data);
  26. expect(result).toEqual({
  27. name: 'John Doe',
  28. age: 30,
  29. email: 'john@example.com'
  30. });
  31. });
  32. it('应该处理嵌套对象中的Promise', async () => {
  33. const nestedSchema = z.object({
  34. user: z.object({
  35. name: z.string(),
  36. profile: z.object({
  37. age: z.number()
  38. })
  39. })
  40. });
  41. const data = {
  42. user: {
  43. name: Promise.resolve('John Doe'),
  44. profile: {
  45. age: Promise.resolve(30)
  46. }
  47. }
  48. };
  49. const result = await parseWithAwait(nestedSchema, data);
  50. expect(result).toEqual({
  51. user: {
  52. name: 'John Doe',
  53. profile: {
  54. age: 30
  55. }
  56. }
  57. });
  58. });
  59. it('当数据不符合schema时应该抛出错误', async () => {
  60. const invalidData = {
  61. name: 'John Doe',
  62. age: 'not-a-number', // 应该是数字
  63. email: 'john@example.com'
  64. };
  65. await expect(parseWithAwait(testSchema, invalidData))
  66. .rejects
  67. .toThrow();
  68. });
  69. it('应该处理数组中的Promise', async () => {
  70. const arraySchema = z.object({
  71. items: z.array(z.object({
  72. name: z.string(),
  73. value: z.number()
  74. }))
  75. });
  76. const data = {
  77. items: [
  78. { name: Promise.resolve('Item 1'), value: 10 },
  79. { name: 'Item 2', value: Promise.resolve(20) }
  80. ]
  81. };
  82. const result = await parseWithAwait(arraySchema, data);
  83. expect(result).toEqual({
  84. items: [
  85. { name: 'Item 1', value: 10 },
  86. { name: 'Item 2', value: 20 }
  87. ]
  88. });
  89. });
  90. });