instantcommerce / next-api-decorators

Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.
https://next-api-decorators.vercel.app
MIT License
409 stars 28 forks source link

Problems when running unit tests with Jest where the ValidationPipe is not triggered. #635

Open arnarleifs opened 11 months ago

arnarleifs commented 11 months ago
The problem When running a unit test using Jest the validation pipeline is not triggered. The expected behaviour would be by providing incorrect values to a route which accepts a body that the validation pipe would be triggered and an error returned to the client. ```javascript // The input model import { IsNumber, IsNotEmpty, IsString, IsOptional } from 'class-validator'; export class UpdateAlbumInputModel { @IsNotEmpty() @IsNumber() albumId: number; @IsOptional() @IsString() description?: string; @IsNotEmpty() @IsString() name: string } // The route @Put('/albums') @HttpCode(204) public async updateAlbums( @Body(ValidationPipe) body: UpdateAlbumInputModel ) { return await this.albumService.updateAlbums(body); } ``` The unit test can be found here: ```javascript it('should fail to update albums, if the body is invalid', async () => { await testApiHandler({ handler: albumHandler, url: '/api/albums', test: async ({ fetch }) => { const res = await fetch({ method: 'PUT', body: JSON.stringify({ description: 'description', }), headers: { 'Content-Type': 'application/json', }, }); // This returns a 204 status code, but expected to return an invalid status code of 400 (Bad Request) console.log(res); }, }); }); ```
Additional context ``` Response { size: 0, timeout: 0, cookies: [Getter], [Symbol(Body internals)]: { body: PassThrough { _readableState: [ReadableState], _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _writableState: [WritableState], allowHalfOpen: true, [Symbol(kCapture)]: false, [Symbol(kCallback)]: null }, disturbed: false, error: null }, [Symbol(Response internals)]: { url: 'http://localhost:53325/', status: 204, statusText: 'No Content', headers: Headers { [Symbol(map)]: [Object: null prototype] }, counter: 0 } } ``` Package versions: `"class-transformer": "0.5.1",` `"class-validator": "0.14.0",` `"next-api-decorators": "2.0.2",`
mykyta-odarchenko commented 10 months ago

Is there any update on this issue? Faced the same problem.