用Jest Expect.toThrow测试猫鼬验证

时间:2019-05-16 13:24:16

标签: typescript mongoose nestjs

我想创建一个测试以确保如果我错过必填字段,服务会引发错误。

这是我的模式:

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

这是我的服务:

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

在我的服务测试中,我遇到了这种情况:

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

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

    });

但是测试失败,并显示以下消息:

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

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我认为您应该像这样修改测试用例:

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

    });

答案 1 :(得分:0)

我自己回答。诀窍是使用Expect.assertions并尝试catch:

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