2

I'm trying to test an async function with Jest and I can't get my test to pass.

My Code

export class UnexpectedRequestError {
  constructor(public message: string = 'Unauthorized') {
    this.message = message;
  }
}

export const foo = async (arg: boolean) => {
  if (arg) {
    return true;
  } else {
    const message = 'message';
    await sendSlackMessage(message);
    throw new UnexpectedRequestError(message);
  }
};

Test Code

test('throws UnexpectedRequestError', async () => {
  await expect(foo(false)).rejects.toThrow(UnexpectedRequestError);
});

My test returns:

expect(received).rejects.toThrow(expected)

Expected constructor: UnexpectedRequestError

Received function did not throw

I've searched for other similar questions here on StackOverFlow but I couldn't find anything wrong with my codes. Any ideas what I'm doing wrong?

7
  • Try except(() => foo(false)). Commented Sep 15, 2022 at 16:09
  • Thanks for your comment. await expect(() => foo(false)).rejects.toThrow(UnexpectedRequestError) gave me the same result, which is Received function did not throw. Commented Sep 16, 2022 at 1:04
  • Make sure that your function will be call with actual logic in your test. Commented Sep 16, 2022 at 1:10
  • @hoangdv I've tried putting console.log('abc') right before throw new UnexpectedRequestError(message) and abc gets displayed when I run the test. Is this what you mean? Commented Sep 16, 2022 at 1:16
  • Yes, it seem something went wrong. Let's try to call await foo(); before the assertion line. Commented Sep 16, 2022 at 1:29

1 Answer 1

4

Your error class needs the "Error" inheritance.

export class UnexpectedRequestError extends Error {
  constructor(public message: string = 'Unauthorized') {
    super(message);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked for me. But is there any other method to solve this? In here throw new Error(err); I am getting this error as I am using ts. No overload matches this call.
You can use your error class, exemple throw new UnexpectedRequestError(err);, maybe worked without this another error.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.