Mnigos
Mnigos

Reputation: 161

How to handle throwing Exceptions in jest

I have created a method that throws exception when provided passsword doesn't match regex. I tried to handle it in 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 protected]',
        pass: 'some pass',
      } as IUser)
    )

    const newUser = await usersService.create({
      name: 'some name',
      email: 'some [email protected]',
      pass: 'some pass',
    })
    expect(newUser).toThrow()
  })

I tried also toThrow('message of error') and toThrow(new BadRequestException()) None of them works.

This is my jest error

 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)

Upvotes: 1

Views: 1496

Answers (1)

Yevhen Laichenkov
Yevhen Laichenkov

Reputation: 8692

You can use the .resolves matcher in your expect statement (and it's recommended one):

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 protected]',
      pass: 'some pass',
    } as IUser),
  );

  // Remove `await` keyword, because you will pass a promise in the expect function
  const newUser = usersService.create({
    name: 'some name',
    email: 'some [email protected]',
    pass: 'some pass',
  });

  // Add `await` keyword and `rejects` matcher with the `toThrow`
  await expect(newUser).rejects.toThrow('Password does not match regex');
});

Also, you can use a simple try/catch statement (but, please don't use it):

it('Should not insert a new user cause password do not match regex', async () => {
  expect.assertions(1)

  jest.spyOn(usersModel, 'create').mockImplementationOnce(() =>
    Promise.resolve({
      name: 'some name',
      email: 'some [email protected]',
      pass: 'some pass',
    } as IUser),
  );

  // Add `try/catch` statement
  try {
    const newUser = await usersService.create({
      name: 'some name',
      email: 'some [email protected]',
      pass: 'some pass',
    });
  } catch (e) {
    expect(e.toString()).toMatch('Password does not match regex');
  }
});

Upvotes: 2

Related Questions