Search code examples
node.jstypescriptjestjsts-jest

Getting "function did not throw" While Testing Async Function to Throw Error with Jest


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?


Solution

  • Your error class needs the "Error" inheritance.

    export class UnexpectedRequestError extends Error {
      constructor(public message: string = 'Unauthorized') {
        super(message);
      }
    }