Handing expected errors in Vitest

By John Keyes

June 25, 2024 at 13:52

javascript javascript testing vitest

A function can raise errors

This toUpper function contains no error handling, so if the value is not a string a TypeError error will be thrown as value will not have a toUpperCase function.

function toUpper(value) {
  return value.toUpperCase(value)
}

This can be verifed by this test:

    expect("123").toBe(toUpper(123));

and it’s corresponding output:

 FAIL  tests/utils.test.js > toUpper numbers
TypeError: value.toUpperCase is not a function
 ❯ Module.toUpper src/utils.js:44:16
     42| 
     43| function toUpper(value) {
     44|   return value.toUpperCase(value)
       |                ^
     45| }
     46| 

Handling expected errors

In this convoluted example this error being thrown is to be expected, and we can verify this using the toThrowError function.

test('toUpper numbers', () => {
  // verify the error type
  expect(() => toUpper(123)).toThrowError(TypeError);
  // verify the error message
  expect(() => toUpper(123)).toThrowError(/not a function/);
});

Note: the calling code must be wrapped in a function or it wouldn’t be possible to test the error afterwards. Without this wrapper function the test runner would exit.

References

Last updated: June 25, 2024 at 13:52