Jose Selesan
Jose Selesan

Reputation: 718

Testing Mongoose Validations with Jest expect.toThrow

I would like to create a test to ensure that if I miss a required field, the service throws an error.

This is my schema:

export const UserSchema = new Schema({
    firstName: String,
    lastName: String,
    email: { type: String, required: true },
    passwordHash: String
});

And this 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();
    }
}

And in my service test I have this case:

it('Validates required email', async () => {
        const dto = {
            firstName: 'Test',
            lastName: 'User',
            passwordHash: '123ABC'
        };

        expect( async () => {
            return await service.create(dto);
        }).toThrowError(/required/);

    });

But the test fails, with this message:

    Expected the function to throw an error matching:
      /required/
    But it didn't throw anything.

Can anybody help me?

Upvotes: 0

Views: 746

Answers (2)

Jose Selesan
Jose Selesan

Reputation: 718

Answer by myself. The trick is to use expect.assertions and try catch:

expect.assertions(1);
try {
    await service.create(dto);
} catch (error) {
    expect(error.message).toMatch(/required/);
}

Upvotes: 0

Ivan Vasiljevic
Ivan Vasiljevic

Reputation: 5718

I think that you should modify your test case like this:

it('Validates required email', async () => {
        const dto = {
            firstName: 'Test',
            lastName: 'User',
            passwordHash: '123ABC'
        };

        await expect(service.create(dto)).rejects.toThrowError(ValidationError); //probably will be error of this type

    });

Upvotes: 2

Related Questions