user19025657
user19025657

Reputation:

How to assert that function throws with a specific error message

I'm using Node v18 ( with the built-in testrunner) and the package assert/strict to test that a function call throws an error with a custom error message.

I think my code should look like

assert.throws(() => myFunction(), 'content of error.message goes here');

Unfortunately I get the following error

error: 'The "error/message" argument is ambiguous. The error message "content of error.message goes here" is identical to the message.'

enter image description here

I also tried

assert.throws(
  () => myFunction(), 
  error => {
    assert.ok(error instanceof CustomError);
    assert.strictEqual(error.message, 'content of error.message goes here');

    return true;
  });

and

assert.throws(myFunction, 'content of error.message goes here');

but unfortunately that didn't help. This might be a duplicate of node assert: Test error message but I don't want to pass in regular expressions because there is no need for it.

Does someone know how to fix the assertion?

Upvotes: 2

Views: 1476

Answers (2)

Der Alex
Der Alex

Reputation: 854

From the docs: https://nodejs.org/api/assert.html#strict-assertion-mode

error cannot be a string. If a string is provided as the second argument, then error is assumed to be omitted and the string will be used for message instead. This can lead to easy-to-miss mistakes. Using the same message as the thrown error message is going to result in an ERR_AMBIGUOUS_ARGUMENT error. Please read the example below carefully if using a string as the second argument gets considered:

and

function throwingSecond() {
  throw new Error('Second');
}

If it was intended to match for the error message do this instead: It does not throw because the error messages match.

assert.throws(throwingSecond, /Second$/);

Upvotes: 0

danh
danh

Reputation: 62676

From the docs, it looks like you can pass an object (and should for the OP case)...

// tests whether the thrown error has a particular message
assert.throws(myFunction, { message: 'content of error.message goes here'});

Upvotes: 3

Related Questions