Asserting exceptions

In the previous examples, we have learned how to assert the type and value of a variable:

const expected = 8; 
expect(result).to.be.a("number"); 
expect(result).to.equal(expected); 

However, there is one scenario that is perhaps not as intuitive as the previous one—testing for an exception.

The MathDemo class also contains a method named bad, which was added with the sole purpose of illustrating how to test for an exception. The bad method throws an exception when it is invoked with a null argument:

public bad(foo: any) { 
  if (foo === null) { 
    throw new Error("Error!"); 
  } else { 
    return this.pow(5, 5); 
  } 
} 

In the following test, we can see how we can use the expect API to assert that an exception is thrown:

it("Should throw ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.