That's because assert.throws
1st parameter takes the function definition, not the function result. It calls the passed function itself. In your example, you're calling the function therefore you're passing the function result.
Instead of this:
assert.throws(myFunc(), output)
Do it like this:
assert.throws(myFunc, output)
If you want to pass parameters to the function under test, you'll need to wrap it in another unnamed function or use Function.bind to bind some arguments to it.
Here's a working example:
const assert = require("assert")
function myFunc(apples) {
if (!apples) {
throw new Error("Apples must have a non-null value");
}
return apples + " are good";
}
describe("myFunc", () => {
it("throws an error if apples is undefined", function() {
const input = undefined;
const output = new Error("Error");
assert.throws(function() {
myFunc(input);
}, output);
})
})
Note that you also need to test that it throws an instance of an Error
instead of a String
.