Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - 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);

Question 1: Does the following work?

expect(fn).toThrow(e);

Question 2: If I've defined an object thing with a method doIt, does the following work?

expect(thing.doIt).toThrow(e);

(2a: 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 js scoping quite enough to be sure.

Thanks!

question from:https://stackoverflow.com/questions/9500586/does-jasmines-tothrow-matcher-require-the-argument-to-be-wrapped-in-an-anonymou

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...