I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest.
it('Should prevent insertion of a new user if the password doesn't match the regex', async () => {
jest.spyOn(usersModel, 'create').mockImplementationOnce(() =>
Promise.resolve({
name: 'some name',
email: 'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff9a929e9693bf9a929e9693d19c9092">[email protected]</a>',
pass: 'some pass',
} as IUser)
)
const newUser = await usersService.create({
name: 'some name',
email: 'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcec6cac2c7ebcec6cac2c785c8c4c6">[email protected]</a>',
pass: 'some pass',
})
expect(newUser).toThrow()
})
I also tried using toThrow('error message')
and
toThrow(new BadRequestException())
, but neither of them worked.
Here is the error message from Jest:
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)