@@ -10,6 +10,10 @@ import * as express from 'express';
1010import { z } from 'zod' ;
1111import { createExpressEndpoints , initServer } from './ts-rest-express' ;
1212import * as multer from 'multer' ;
13+ import {
14+ CombinedRequestValidationErrorSchema ,
15+ DefaultRequestValidationErrorSchema ,
16+ } from './request-validation-error' ;
1317
1418const upload = multer ( ) ;
1519
@@ -468,4 +472,88 @@ describe('ts-rest-express', () => {
468472 expect ( res . body ) . toEqual ( { message : 'Not found' } ) ;
469473 } ) ;
470474 } ) ;
475+
476+ it ( "should throw default requestValidation error if body doesn't match" , async ( ) => {
477+ const contract = c . router ( {
478+ createPost : {
479+ method : 'POST' ,
480+ path : '/posts' ,
481+ body : z . object ( {
482+ id : z . string ( ) ,
483+ content : z . string ( ) ,
484+ } ) ,
485+ responses : {
486+ 200 : c . noBody ( ) ,
487+ 400 : DefaultRequestValidationErrorSchema ,
488+ } ,
489+ } ,
490+ } ) ;
491+
492+ const router = s . router ( contract , {
493+ createPost : async ( ) => {
494+ return {
495+ status : 200 ,
496+ body : undefined ,
497+ } ;
498+ } ,
499+ } ) ;
500+
501+ const app = express ( ) ;
502+ app . use ( express . json ( ) ) ;
503+ app . use ( express . urlencoded ( { extended : true } ) ) ;
504+ createExpressEndpoints ( contract , router , app , {
505+ requestValidationErrorHandler : 'default' ,
506+ } ) ;
507+
508+ await supertest ( app )
509+ . post ( '/posts' )
510+ . expect ( ( res ) => {
511+ expect ( res . status ) . toEqual ( 400 ) ;
512+ expect ( ( ) =>
513+ DefaultRequestValidationErrorSchema . parse ( res . body ) ,
514+ ) . not . toThrowError ( ) ;
515+ } ) ;
516+ } ) ;
517+
518+ it ( "should throw combined requestValidation error if body doesn't match" , async ( ) => {
519+ const contract = c . router ( {
520+ createPost : {
521+ method : 'POST' ,
522+ path : '/posts' ,
523+ body : z . object ( {
524+ id : z . string ( ) ,
525+ content : z . string ( ) ,
526+ } ) ,
527+ responses : {
528+ 200 : c . noBody ( ) ,
529+ 400 : DefaultRequestValidationErrorSchema ,
530+ } ,
531+ } ,
532+ } ) ;
533+
534+ const router = s . router ( contract , {
535+ createPost : async ( ) => {
536+ return {
537+ status : 200 ,
538+ body : undefined ,
539+ } ;
540+ } ,
541+ } ) ;
542+
543+ const app = express ( ) ;
544+ app . use ( express . json ( ) ) ;
545+ app . use ( express . urlencoded ( { extended : true } ) ) ;
546+ createExpressEndpoints ( contract , router , app , {
547+ requestValidationErrorHandler : 'combined' ,
548+ } ) ;
549+
550+ await supertest ( app )
551+ . post ( '/posts' )
552+ . expect ( ( res ) => {
553+ expect ( res . status ) . toEqual ( 400 ) ;
554+ expect ( ( ) =>
555+ CombinedRequestValidationErrorSchema . parse ( res . body ) ,
556+ ) . not . toThrowError ( ) ;
557+ } ) ;
558+ } ) ;
471559} ) ;
0 commit comments