I'm looking to create a testing scenario to verify that if I forget to fill out a required field, the service will generate an error message.
Here is my schema:
export const UserSchema = new Schema({
firstName: String,
lastName: String,
email: { type: String, required: true },
passwordHash: String
});
And here is my service:
@Injectable()
export class UsersService {
constructor(@InjectModel('User') private readonly userModel: Model<User>) {}
async create(createUserDto): Promise<User> {
const createdUser = new this.userModel(createUserDto);
return await createdUser.save();
}
}
Within my service test, I have the following case:
it('Validates email as required', async () => {
const dto = {
firstName: 'Test',
lastName: 'User',
passwordHash: '123ABC'
};
expect( async () => {
return await service.create(dto);
}).toThrowError(/required/);
});
However, the test is not passing and I am receiving this error message:
Expected the function to throw an error matching:
/required/
But it didn't throw anything.
Any suggestions on how to address this issue?