Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Jasmine's toThrow matcher require the argument to be wrapped in an anonymous function?

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.

like image 667
brahn Avatar asked Feb 29 '12 14:02

brahn


2 Answers

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 bind can be used with Jasmine.

describe('using bind with jasmine', function() {      var f = function(x) {         if(x === 2) {             throw new Error();         }     }      it('lets us avoid using an anonymous function', function() {         expect(f.bind(null, 2)).toThrow();     });  }); 

The first argument provided to bind is used as the this variable when f is called. Any additional arguments are passed to f when it is invoked. Here 2 is being passed as its first and only argument.

like image 188
Danyal Aytekin Avatar answered Nov 01 '22 23:11

Danyal Aytekin


Let’s take a look at the Jasmine source code:

try {   this.actual(); } catch (e) {   exception = e; } if (exception) {   result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); } 

This is the core part of the toThrow method. So all the method does is to execute the method you want to expect and check if a exception was thrown.

So in your examples, fn or thing.doIt will be called in the Jasmine will check if an error was thrown and if the type of this error is the one you passed into toThrow .

like image 27
Andreas Köberle Avatar answered Nov 01 '22 23:11

Andreas Köberle