validateReq.test.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { parseReq } from '../../../parseReq'
  2. import { describe, expect, it } from 'vitest'
  3. import { z } from 'zod'
  4. import type { Request } from 'express'
  5. import { zz } from '../../../zodHelpers'
  6. describe('parseReq', () => {
  7. describe('with a request that is valid for the schema', () => {
  8. it('should return the parsed request', () => {
  9. const req = {
  10. params: {
  11. id: '507f1f77bcf86cd799439011',
  12. },
  13. body: {
  14. name: 'Valid Name',
  15. },
  16. } as Request<{ id: string }, any, { name: string }>
  17. const schema = z.object({
  18. params: z.object({
  19. id: zz.objectId(),
  20. }),
  21. body: z.object({
  22. name: z.string(),
  23. }),
  24. })
  25. const result = parseReq(req, schema)
  26. expect(result).toEqual({
  27. params: {
  28. id: '507f1f77bcf86cd799439011',
  29. },
  30. body: {
  31. name: 'Valid Name',
  32. },
  33. })
  34. })
  35. })
  36. describe('with a request that is not valid for the schema', () => {
  37. it('should throw NotFoundError if params are invalid', () => {
  38. const req = {
  39. params: {
  40. id: 'invalid-object-id',
  41. },
  42. } as Request<{ id: string }>
  43. expect(() =>
  44. parseReq(
  45. req,
  46. z.object({
  47. params: z.object({
  48. id: zz.objectId(),
  49. }),
  50. })
  51. )
  52. ).toThrowError(expect.objectContaining({ name: 'ParamsError' }))
  53. })
  54. it('should throw an error containing issues if the schema is invalid', () => {
  55. const req = {
  56. body: {
  57. name: 1234,
  58. },
  59. } as Request
  60. expect(() =>
  61. parseReq(
  62. req,
  63. z.object({
  64. body: z.object({
  65. name: z.string(),
  66. }),
  67. })
  68. )
  69. ).toThrowError(
  70. expect.objectContaining({
  71. issues: expect.arrayContaining([
  72. expect.objectContaining({ path: ['body', 'name'] }),
  73. ]),
  74. })
  75. )
  76. })
  77. })
  78. })