Reputation:
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.'
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
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