Jasmine 2.0如何在运行期望之前等待实时

sil*_*min 14 javascript jasmine

我正在尝试测试postMessage API,因为在收到消息之前有一点延迟我发送消息后无法立即运行期望.

在jasmine 1.3中我习惯等待()几毫秒才能运行期望,并且运行正常.然而,对于jasmine 2.0,wait()已被弃用,现在似乎setTimeout中的所有内容都不会运行,除非调用done(),在我的情况下,女巫不会削减它,因为我实际上想要在运行我的期望之前等待实时..

不确定这一切是否有意义,如果确实如此,我会喜欢关于如何解决这个问题的一些指示.谢谢!

sid*_*mor 11

这对我有用:

beforeAll(function (done) {
    setTimeout(done, 5000);
});
Run Code Online (Sandbox Code Playgroud)

beforeAll函数首先发生,但是当你调用done回调函数时它会结束.因此,如果您使用5000的setTimeout函数,它将等待5000毫秒,然后继续.


Jef*_*rey 6

而不是等待一些毫秒,jasmine有挂钩等待函数返回.这个页面有一些很好的例子,我在这里复制了一个,以显示测试ajax回调的特定方法.只需添加一个间谍作为函数的回调,并等待执行该回调.

it("should make a real AJAX request", function () {
    var callback = jasmine.createSpy();
    makeAjaxCall(callback);
    waitsFor(function() {
        return callback.callCount > 0;
    }, "The Ajax call timed out.", 5000);

    runs(function() {
        expect(callback).toHaveBeenCalled();
    });
});
Run Code Online (Sandbox Code Playgroud)

编辑:

由于您正在测试应用程序是否进行了特定的回调,因此您只需用间谍替换该回调,而不是像我一样创建新的回调.

Jasmine 2.0添加了一个"完成"样式的回调,所以你应该能够做到这样的事情:(我没有测试过这个的语法,但希望是一个好的开始)

it("should make an ajax callback with jasmine 2.0", function(done)) {
    // this is the object you are testing - assume it has the ajax method you want to call and the method that gets called when the ajax method is finished
    var myObject
    spyOn(myObject, "callback").andCallFake(function() {
        done();        
    });    
    myObject.makeAjaxCall();    
}
Run Code Online (Sandbox Code Playgroud)