The documentation at https://github.com/pivotal/jasmine/wiki/Matchers includes the following:
expect(function(){fn();}).toThrow(e);
As discussed in this question, the following does not work, because we want to pass a function object to expect rather than the result of calling fn():
expect(fn()).toThrow(e);
Does the following work?
expect(fn).toThrow(e);
If I’ve defined an object thing with a method doIt, does the following work?
expect(thing.doIt).toThrow(e);
(If so, is there a way to pass arguments to the doIt method?)
Empirically the answer seems to be yes, but I don’t trust my understanding of JavaScript scoping quite enough to be sure.
We can do away with the anonymous function wrapper by using
Function.bind, which was introduced in ECMAScript 5. This works in the latest versions of browsers, and you can patch older browsers by defining the function yourself. An example definition is given at the Mozilla Developer Network.Here’s an example of how
bindcan be used with Jasmine.The first argument provided to
bindis used as thethisvariable whenfis called. Any additional arguments are passed tofwhen it is invoked. Here2is being passed as its first and only argument.