#typescript: Dates in controller response are not Dates but are strings; numbers are numbers though

1 messages · Page 1 of 1 (latest)

small pebble
#

I have a response object that looks like this
class MyResponse {
id: string;
qty: number;
paid: Date;
}

My controller looks like
@Get("/test")
async test(): Promise<MyResponse> {
const res: MyResponse = {
id: 'hi',
qty: 1,
paid: new Date(),
}
return res;
}

In my swagger and in my unit test however, my responses look like
{
id: 'hi',
qty: 1,
paid: 'string-ified version'
}

The qty is coming across as a number but why is the date coming across as not a Date object? Why is it a string? I'm asking because I can't get my e2e test to pass because of the type mis-match. I would really prefer it to be of type Date and not string anyway. Is there a way to force nest to serialize it properly? I've tried adding a ValidationPipe to that endpoint as well as having an @Transform on my paid field.

amber cradle
#

Because JSON does not have a Date type.

small pebble
#

That's true, I just assumed that the nestjs e2e test harness (as documented) would have transformed Dates into Dates

echo pawn
#

Transformation into Date must be performed on the client. Nest has no power there. It would be wrong to transform it in tests and have it break in a real application

small pebble
#

So how does one perform assertions on dates? I had hoped to just one-line it with a jest expect(expectedResponse).toStrictEqual(actoualResponse)
In my real life example the objects are very complicated with lots of nested arrays of objects and dates all over.

#

We're talking hundreds of fields. So doing individual expects on every field in the response isn't going to be maintainable.