zodHelpers.test.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { zz } from '../../../zodHelpers'
  2. import { describe, expect, it } from 'vitest'
  3. import mongodb from 'mongodb'
  4. const { ObjectId } = mongodb
  5. describe('zodHelpers', () => {
  6. describe('objectId', () => {
  7. it('fails to parse when provided with an invalid ObjectId', () => {
  8. const parsed = zz.objectId().safeParse('aa')
  9. expect(parsed.success).toBe(false)
  10. expect(parsed.error?.issues).toHaveLength(1)
  11. expect(parsed.error?.issues).toMatchObject([
  12. expect.objectContaining({
  13. message: 'invalid Mongo ObjectId',
  14. }),
  15. ])
  16. })
  17. it('parses successfully when provided with a valid ObjectId', () => {
  18. const parsed = zz.objectId().safeParse('507f1f77bcf86cd799439011')
  19. expect(parsed.success).toBe(true)
  20. expect(parsed.data).toBe('507f1f77bcf86cd799439011')
  21. })
  22. })
  23. describe('coercedObjectId', () => {
  24. it('fails to parse when provided with an invalid ObjectId', () => {
  25. const parsed = zz.coercedObjectId().safeParse('aa')
  26. expect(parsed.success).toBe(false)
  27. expect(parsed.error?.issues).toHaveLength(1)
  28. expect(parsed.error?.issues).toMatchObject([
  29. expect.objectContaining({
  30. message: 'invalid Mongo ObjectId',
  31. }),
  32. ])
  33. })
  34. it('parses to an ObjectId when provided with a valid ObjectId string', () => {
  35. const parsed = zz.coercedObjectId().safeParse('507f1f77bcf86cd799439011')
  36. expect(parsed.success).toBe(true)
  37. expect(parsed.data).toBeInstanceOf(ObjectId)
  38. expect(parsed.data?.toString()).toBe('507f1f77bcf86cd799439011')
  39. })
  40. })
  41. })