.toThrow(error)

Also under the alias: .toThrowError(error)

Use .toThrow to test that a function throws when it is called. For example, if we want to test that drinkFlavor('octopus') throws, because octopus flavor is too disgusting to drink, we could write:

  1. test('throws on octopus', () => {
  2. expect(() => {
  3. drinkFlavor('octopus');
  4. }).toThrow();
  5. });

To test that a specific error is thrown, you can provide an argument:

  • regular expression: error message matches the pattern
  • string: error message includes the substring
  • error object: error message is equal to the message property of the object
  • error class: error object is instance of class
    For example, let's say that drinkFlavor is coded like this:
  1. function drinkFlavor(flavor) {
  2. if (flavor == 'octopus') {
  3. throw new DisgustingFlavorError('yuck, octopus flavor');
  4. }
  5. // Do some other stuff
  6. }

We could test this error gets thrown in several ways:

  1. test('throws on octopus', () => {
  2. function drinkOctopus() {
  3. drinkFlavor('octopus');
  4. }
  5. // Test that the error message says "yuck" somewhere: these are equivalent
  6. expect(drinkOctopus).toThrowError(/yuck/);
  7. expect(drinkOctopus).toThrowError('yuck');
  8. // Test the exact error message
  9. expect(drinkOctopus).toThrowError(/^yuck, octopus flavor$/);
  10. expect(drinkOctopus).toThrowError(new Error('yuck, octopus flavor'));
  11. // Test that we get a DisgustingFlavorError
  12. expect(drinkOctopus).toThrowError(DisgustingFlavorError);
  13. });
Note: You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail.