#class-transformer transform objects to string

1 messages · Page 1 of 1 (latest)

craggy beacon
#

I'm using NestJS with class-validator and class-transformer, I run Jest tests with the following configuration

app.useGlobalPipes(
  new ValidationPipe({
  skipMissingProperties: false,
  skipUndefinedProperties: false,
  forbidNonWhitelisted: false,
  whitelist: true,
  transform: true,
  transformOptions: {
    enableImplicitConversion: true
  }
  })
);

I use the transform: true and enableImplicitConversion: true because otherwise numbers don't get transformed correctly, and for reusability I don't use pipes like ParseIntPipe and such because I have a lot of schemas and adding a pipe for each one will take forever,
When I'm testing using Jest + Fastify, whenever I send an object it gets transformed into string ([object Object]) and therefore passes IsString() validation, is that an expected behavior? because I don't think it should be
This is the test (which passed but shouldn't)

const commentContent = { a: 6 };
const body = { content: commentContent };
// Act
const result = await testEnvironment.app.inject({
    method: "POST",
    url: "api/v1/comment",
    payload: JSON.stringify(body),
    headers: { "content-type": "application/json" }
});

and this is the schema for the route:

export class CommentCreateSchema {
    @IsString()
    @MinLength(1)
    @MaxLength(1023)
    content!: string;
}

Thanks upfront!

crystal lake
#

What if you don't JSON.stringify?

craggy beacon
#

Same result

crystal lake
#

Does your test environment bind the validation pipe?

craggy beacon
#

Yes, when I try to put empty string in content I get a validation error:

    Received: "content must be longer than or equal to 1 characters"
sick wraith
#

not an answer directly, but what if you wrap commentContent with a quote as if it was a real input from a frontend textfield? would look like "{a: 6}"

Just a suggestion though maybe could help.