如何在玩笑中处理抛出异常

How to handle throwing Exceptions in jest

我创建了一个方法,当提供的密码与正则表达式不匹配时会抛出异常。我试图在 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()) None 其中有效。

这是我开玩笑的错误

 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 语句中使用 .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');
  }
});