为什么在Jasmine中,我们不能将expect放在外部函数中

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

本文关键字:expect 外部 函数 我们 Jasmine 为什么 不能      更新时间:2023-09-26

如果使用Jasmine 1.3.1,我使用

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

和foo只是:

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

我希望它检查0到4,并打印出

HERE 0
THERE 0
HERE 1
THERE 1
  ...

但是,它只是在Chrome的控制台中打印为:HERE 0, HERE 1, ...然后THERE 5五次。有人知道为什么expect不能放在像这样的外部函数中,如果我需要将许多步骤放入函数中,该在Jasmine中做什么?

作为旁注,有时在JavaScript中,我感觉像开发了一种全新的语言,通常可以做的事情将不起作用-并且想知道可以做些什么来防止这种类型的事情发生,一些不知道会发生的事情。

如果你想尝试一下,它在https://github.com/jianlin/jasmine-looping-an-it-calling-function-that-does-expect

我从来没有使用过Jasmine,所以我不知道这做了什么,我绝对不知道it做了什么,但这似乎是Javascript中常见的闭包问题。

这通常发生在异步(如event处理程序)试图访问回调中的迭代器(i)时。到那时,循环已经结束,i是最后一个值。使用闭包,可以捕获i的值并正确传递。如果it是异步的,你将无法得到你想要的console.log结果的顺序——"HERE"将先出现,然后是"THERE"。

你可以试试下面的代码:

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