I am trying to use Nest.js with the class-validator package in order to make sure that an User-provided email field is not empty & that a User-given password has at least 8 characters.
I have a user-model-user.ts file where my User class exists with the decorators below:
import {IsNotEmpty, MinLength} from 'class-validator';
export class User {
@IsNotEmpty()
email: string;
@IsNotEmpty()
@MinLength(8)
password:string;
}
In my test file I have the tests
user-user.controller.spec.ts
it('when email is empty, then return error 400', (done) => {
const user = createUser();
user.email = '';
validate(user).catch((error) => {
expect(error.getResponse().statusCode).toEqual(400);
done();
});
});
it('when password is less than 8 characters, return error 400', (done) => {
const user = createUser();
user.password = '12345678';
validate(user).catch((error) => {
expect(error.getResponse().statusCode).toEqual(400);
done();
});
})
function createUser() {
return {
email: '[email protected]',
password: '1234567'
};
}
function validate(user:User) {
const validationPipe = new ValidatorPipe({transform: true});
return validationPipe.transform(user, {
type: 'body',
metatype: User
});
}
});
After looking online and at this code for a long time while fixing bracket placements, I am unable to find out why my tests are passing when the ’email’ field is empty in the first lines of my user.controller.spec.ts file. In the same test mentioned above, my password field is less than 8 characters and also passes as, when I really wanted it to fail since it is less than 8 characters.
However, I notice that in my second ‘it’ test, when the user.password field is 8 characters or more, the test for it fails. I see the reason for it failing is because of an “Exceeded timeout of 5000ms for a test” error when in reality I would like it to pass since it contains a minimum of 8 characters like I described in my model-user.ts file.
Does someone see what I’m doing wrong here?