next-api-decorators
next-api-decorators copied to clipboard
Problems when running unit tests with Jest where the ValidationPipe is not triggered.
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.
// 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:
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",