【发布时间】:2021-09-07 19:56:44
【问题描述】:
我创建了一个在提供的密码与正则表达式不匹配时引发异常的方法。我试图在 Jest 中处理它
it('Should not insert a new user cause password do not match regex', async () => {
jest.spyOn(usersModel, 'create').mockImplementationOnce(() =>
Promise.resolve({
name: 'some name',
email: 'some email@email.com',
pass: 'some pass',
} as IUser)
)
const newUser = await usersService.create({
name: 'some name',
email: 'some email@email.com',
pass: 'some pass',
})
expect(newUser).toThrow()
})
我也试过toThrow('message of error')
和toThrow(new BadRequestException())
它们都不起作用。
这是我开玩笑的错误
UsersService › Should not insert a new user cause password do not match regex
Password does not match regex
49 | const emailRegex = /[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+/
50 |
> 51 | if (!pass.match(passRegex)) throw new BadRequestException('Password does not match regex')
| ^
52 | if (!email.match(emailRegex)) throw new BadRequestException('Email does not match regex')
53 |
54 | const saltRounds = 10
at UsersService.create (users/users.service.ts:51:39)
at Object.<anonymous> (users/users.service.spec.ts:135:21)
【问题讨论】:
-
您需要传递一个 函数 以期望它抛出,否则错误会发生在 到达
expect之前:jestjs.io/docs/expect#tothrowerror。或者你可以使用.rejects:jestjs.io/docs/asynchronous#resolves--rejects。
标签: javascript typescript exception jestjs nestjs