0

In my function I use:

  if (apples === undefined) {
    throw new Error('Error');
  }

In my test I am trying to confirm this is working by doing:

  it('throw an error if apples is undefined', function() {
    const input = undefined;
    const output = "Error";
    assert.throws(myFunc(input), output);
  });

However I get:

1 failing

  1. myFunc should throw an error if apples is undefined: Error Error
GTA.sprx
  • 817
  • 1
  • 8
  • 24
  • 2
    Does this answer your question? [Node assert.throws not catching exception](https://stackoverflow.com/questions/6645559/node-assert-throws-not-catching-exception) – nicholaswmin Jul 27 '20 at 07:51

1 Answers1

0

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.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167