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

前端 未结 4 499
忘了有多久
忘了有多久 2020-12-05 09:29

The documentation at https://github.com/pivotal/jasmine/wiki/Matchers includes the following:

expect(function(){fn();}).toThrow(e);

As disc

4条回答
  •  长情又很酷
    2020-12-05 10:20

    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.

提交回复
热议问题