5

Using node's assert module how can I test the message of an error?

throw new Error('Email is required!');

I'm using assert.throws to check if an error was thrown:

assert.throws(myFunction, Error);

But this does not provide the ability to check the message.

mosquito87
  • 4,270
  • 11
  • 46
  • 77

2 Answers2

6

You can pass a regular expression as the second argument.

assert.throws(myFunction, /Email is required/);
JME
  • 3,592
  • 17
  • 24
0

You can assert a full error object, including the message without using regular expressions:

assert.throws(myFunction, new Error("Email is required"));

This way it also asserts the correct error name (class).

Maxim Mazurok
  • 3,856
  • 2
  • 22
  • 37
  • JME's answer works for me, but if I use this one I get: `TypeError: The argument 'error' may not be an empty object.` In this case `error` is created with `new Error("some text")` – Chris Chiasson Aug 01 '22 at 19:32
  • @ChrisChiasson it works for me. This error happens when the second argument to `assert.throws()` is an empty object. Make sure you're not importing `Error` from somewhere.. – Maxim Mazurok Aug 02 '22 at 00:41
  • My guess is that it is related to typescript. On my computer, a typescript test file with total contents equal to the following triggers the error: https://pastebin.com/NgzzPWt8 – Chris Chiasson Aug 02 '22 at 03:29
  • @ChrisChiasson I've added your code to [my project](https://github.com/Maxim-Mazurok/google-api-typings-generator) and it works fine. Try `console.log(Error)`, it should be `[Function: Error] { stackTraceLimit: Infinity, prepareStackTrace: [Function: prepareStackTrace] }` – Maxim Mazurok Aug 02 '22 at 07:10
  • Sorry I forgot about this. Clearly there is something going on because the solution from JME is getting a lot of upvotes (including mine), but at least the next person to come along (possibly even myself at a future date) will have this thread to pick up on if they have time to run down the true source of the problem. Wanted to say thanks for your help Maxim! – Chris Chiasson Nov 01 '22 at 15:28