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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)