nonopolarity
nonopolarity

Reputation: 151026

Why in Jasmine, we cannot put the expect in an outside function?

If using Jasmine 1.3.1, I use

describe("TryTry", function() {

    var i;

    function checkForSituation(a) {
        // say, if this is made into a function because 
        //   there are a lot of processing

        console.log("THERE", a); 
        expect(foo(3, a)).toEqual( 3 + a );
    }

    for (i = 0; i < 5; i++) {
        console.log("HERE", i); 

        it("should add for " + i, function() {

            checkForSituation(i);

        });

    }

});

and foo is just:

function foo(a, b) {
    return a + b;
}

I would expect it to check for 0 to 4, and print out

HERE 0
THERE 0
HERE 1
THERE 1
  ...

but instead, it just print in Chrome's console as: HERE 0, HERE 1, ... and then THERE 5 five times. Does somebody know why an expect cannot be put in an outside function like that and what to do in Jasmine if I need to put many steps into a function?

As a side note, sometimes in JavaScript, I feel like a whole new language is developed and what you can usually do won't work -- and wonder what can be done to prevent this type of things from happening, something without knowing that it would happen.

If you'd like to try it out, it is on https://github.com/jianlin/jasmine-looping-an-it-calling-function-that-does-expect

Upvotes: 0

Views: 358

Answers (1)

Ian
Ian

Reputation: 50905

I've never used Jasmine, so I don't know what most of this does, and I definitely don't know what it does, but this seems to be the common closure problem in Javascript.

This usually happens when something asynchronous (like an event handler) tries to access the iterator (i) in its callback. By that time, the loop has finished and i is the last value. Using a closure, the value of i could be captured and be passed properly. If it is asynchronous, you won't be able to get the order of console.log results you wanted - the "HERE" will come first, then the "THERE".

You could try this code:

it("should add for " + i, (function(i) {
    return function () {
        checkForSituation(i);
    };
})(i);

Upvotes: 1

Related Questions