zodValidate.test.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { afterEach, describe, expect, it, vi } from 'vitest';
  2. import { z } from 'zod';
  3. import { HttpUtil, Msg } from '@/utils';
  4. import { parseMsg } from '@/utils/zodValidate';
  5. import { ClientPageResponseSchema } from '@/schemas/client';
  6. import { fetchXrayConfig } from '@/hooks/useXraySetting';
  7. afterEach(() => {
  8. vi.restoreAllMocks();
  9. });
  10. describe('parseMsg', () => {
  11. it('rejects a successful response whose payload violates its schema', () => {
  12. const msg = new Msg(true, '', { id: 'not-a-number' });
  13. const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
  14. expect(() => parseMsg(msg, z.object({ id: z.number() }), 'test/value', { strict: true })).toThrow(
  15. 'test/value response failed validation',
  16. );
  17. expect(warning).toHaveBeenCalledWith(
  18. '[zod] test/value response failed validation',
  19. expect.arrayContaining([expect.objectContaining({ code: 'invalid_type', path: ['id'] })]),
  20. );
  21. });
  22. it('preserves a missing successful payload for callers that handle empty values', () => {
  23. expect(parseMsg(new Msg(true, '', null), z.object({ id: z.number() }), 'test/value').obj).toBeNull();
  24. });
  25. it('rejects malformed paged-client payloads', () => {
  26. const payload = { items: [], total: 'one', filtered: 1, page: 1, pageSize: 20 };
  27. const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
  28. expect(() => parseMsg(new Msg(true, '', payload), ClientPageResponseSchema, 'clients/list/paged', { strict: true })).toThrow(
  29. 'clients/list/paged response failed validation',
  30. );
  31. expect(warning).toHaveBeenCalledWith(
  32. '[zod] clients/list/paged response failed validation',
  33. expect.arrayContaining([expect.objectContaining({ code: 'invalid_type', path: ['total'] })]),
  34. );
  35. });
  36. });
  37. describe('fetchXrayConfig', () => {
  38. it('keeps a malformed xray payload available for repair', async () => {
  39. vi.spyOn(HttpUtil, 'post').mockResolvedValue(new Msg(true, '', JSON.stringify({ xraySetting: 'not-an-object' })));
  40. const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
  41. await expect(fetchXrayConfig()).resolves.toEqual({ xraySetting: 'not-an-object' });
  42. expect(warning).toHaveBeenCalledWith(
  43. '[zod] xray/ config payload failed validation',
  44. expect.arrayContaining([expect.objectContaining({ code: 'invalid_type', path: ['xraySetting'] })]),
  45. );
  46. });
  47. });