3

I'm working in the fontend side, and testing my library, I receive an error that I expect but I cannot make an assertion. I have the next code:

it('If the username is not entered, I get an error', () => {
    try {
      new SDK('test', {
        password: 'aaaabbbbcccc',
        key: 'ddddeeefff',
      });
    } catch (error) {
      expect(error).toThrow(
        `Error: The 'username' property has not been entered`
      );
    }
  });

As you can see, for the authentication of my library, I need: username, password and key. This is the error that I get:

enter image description here

Thank you!

1 Answer 1

14

I found my problem. It was necessary for the "expect" to catch the exception and then use the appropriate matcher (without try/catch block)

it('If the username is not entered, I get an error', () => {
  expect(() => {
    new SDK('test', {
      password: 'aaaabbbbcccc',
      key: 'ddddeeefff',
    });
  }).toThrowError(`The 'username' property has not been entered`);
});
3
  • 3
    i kind of had a similar experience.. Where i used await expect(S3Client.getObject(s3Param.bucket, s3Param.key)).rejects.toThrow("The resource you requested does not exist"); Dec 1, 2020 at 19:44
  • 1
    saved me from wasting too much time as I was using try()-catch{} at first. Thank you
    – MSadiq
    Sep 21, 2022 at 8:53
  • 3
    And if it's async and you're awaiting a promise then .rejects.toThrowError should work!
    – Kitson
    Jan 5 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.