Skip to content

Use "toThrowError" and "toThrow" in TypeScript with Objects

March 2nd, 2017 - Software

TL;DR: wrap your method call in the expect() statement. Instead of expect(obj.method()).toThrow(), write expect( () => { obj.method() }).toThrow().

While in the process of improving the code coverage, I needed to write a test for a method throwing an exception. My initial code would have been something like:

import { SelectorComponent } from './selector-component'

describe('SelectorComponent', () => {
  let selectorComponent: SelectorComponent

  it('should throw error when toggle is not defined', () => {
    selectorComponent = new SelectorComponent()

    expect(selectorComponent.updateSelectors('undef_key')).toThrow()
  })
})

Where SelectorComponent has a method named updateSelectors(value: any) which throws an error if the value is not in an array.

If I write the test as above, it will fail (the test itself will throw the error):

SelectorComponent
    × should throw error when toggle is not defined
      Electron 1.4.15 (Node 6.5.0)
    TypeError: Value [undef_key] does not exist in the list of toggles.
        at SelectorComponent.updateSelectors (webpack:///src/app/settings/selector-component.ts:9:737 <- karma-spec.js:49169:744)

However, If I write the test as:

expect(() => {
  selectorComponent.updateSelectors('undef_key')
}).toThrow()

The test will complete nicely with the error being caught and processed by the test suite.

Same approach is valid for toThrowError() :)

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: