2
votes

I need to call expect().to.throw() on a function that takes arguments. For example, say I have the following:

var func = function(x) {
  if (x > 1) {
    throw new Error()
  } else {
    console.log('hello')
  }
}
expect(func).to.throw()

This fails, because it calls func without an argument, meaning it will never throw an error. But if I call expect(func(2)).to.throw(), I get AssertionError: expected undefined to be a function. The function gets called and the return value is passed to expect.

How can I use expect().to.throw() and give the included function arguments. Is the only way to do it with an anonymous function, like expect(() => {func(2)}).to.throw()?

1

1 Answers

6
votes

This is from the chai docs:

If you need to assert that your function fn throws when passed certain arguments, then wrap a call to fn inside of another function.

expect(function () { fn(42); }).to.throw();  // Function expression
expect(() => fn(42)).to.throw();             // ES6 arrow function