fbpx

27 Apr /Testing exceptions with Async Await

Posted by Dom Miller

Normally when testing your code throwing exceptions is goes something like this: (examples in typescript with Jasmine)


function isTwo(num: number): number {
  if(num != 2) throw new Error("Yo! It's not number 2!!");
  return num;
}

// ... inside describe block
it("should throw an error", () => {
  const throwError = function() { isTwo(3) };

  expect(throwError).toThrowError("Yo! It's not number2!!")
}

We wrap our function in an anonymous function and pass it to the expectation.  All is good and we move on with our day!

But what if our function is returning a promise! Aha, things can’t work the same.

Let’s use async / await to help us.


function isTwo(num: number): Promise<number> {
  new Promise(resolve, reject) {
    if(num != 2) reject("Yo! It's not number 2!!");
    resolve(num);
  }
}

// ... inside describe block
it("should throw an error", async () => {
  try {
    const throwError = isTwo(3); 
  } catch(error) {
    expect(error.message).toBe(""Yo! It's not number 2!!");
  }
}