【问题标题】:How to handle throwing Exceptions in jest如何处理开玩笑的抛出异常
【发布时间】: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)

【问题讨论】:

标签: javascript typescript exception jestjs nestjs


【解决方案1】:

您可以在期望语句中使用.resolves 匹配器(推荐使用):

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),
  );

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

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

另外,您可以使用简单的try/catch 语句(但请不要使用它):

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@email.com',
      pass: 'some pass',
    } as IUser),
  );

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

【讨论】:

  • 你应该在测试中像这样使用try/catch;如果没有抛出错误,则不会达到任何期望,因此测试通过。在这种情况下,您需要使用例如expect.assertions 确保测试在正确的情况下失败,正如我在 stackoverflow.com/a/62513421/3001761 中展示的那样。
  • 嘿@jonrsharpe。感谢您的评论。公平点,我已经更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 2013-07-24
  • 2020-10-23
相关资源
最近更新 更多