在测试JavaScript时,还有比setTimeout更好的方法来等待asnyc回调吗? [英] Any better way than setTimeout to wait for asnyc callbacks when testing JavaScript?

查看:86
本文介绍了在测试JavaScript时,还有比setTimeout更好的方法来等待asnyc回调吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此代码:

showForm = function (url) {
        return $.get(url, function (html) {
             $('body').append();              
        });
 };

使用 sinon.js 时, jQuery.mockjax.js expect.js ,我有以下通过测试:

When using sinon.js, jQuery.mockjax.js and expect.js, I have the following passing test:

it("showForm calls jQuery.append", function () {

    $.mockjax({
          url: '/fake'                    
    });

    var spy = sinon.spy($.fn, "append");             
    presenter.showForm('/fake');

    setTimeout(function () { 
        expect(spy.called).to.be.equal(true);
    }, 1000);
});

使用 setTimeout 函数等待来自异步 $。get 的回调闻起来很糟糕,如果我做了太多的话,它会减慢我的测试套件。

Using the setTimeout function to wait on the callback from the asynchronous $.get smells bad and it will slow down my test suite if I do too much of it.

然而,我觉得这个意图相当清楚,而且它似乎确实测试了我想要的东西。

However, I feel that the intent is reasonably clear and it does seem to test exactly what I want.

有没有更好的方法,请你解释一下是什么在你的答案中继续?

Is there a better way and can you please explain what's going on in your answer?

推荐答案

传递你的匿名函数将表单显示为参数并在回调后调用它附加。为了确保它被调用,你可以使它成为一个$ .ajax请求,它也包含错误回调。

Pass your anonymous function to show form as a parameter and have it called in the callback after the append. To ensure its called you could make it an $.ajax request that covers the error callback as well.

这样就可以在get请求完成且没有多余时间或过早调用时调用它。

This way it is called exactly when the get request finishes with no excess time or called too early.

showForm = function (url, callback) {
        return $.get(url, function (html) {
             $('body').append();   
             if(callback != undefined)
             callback();
        });
 };

it("showForm calls jQuery.append", function () {

    $.mockjax({
          url: '/fake'                    
    });

    var spy = sinon.spy($.fn, "append");

    presenter.showForm('/fake', function (){ 
        expect(spy.called).to.be.equal(true);
    });
});

这篇关于在测试JavaScript时,还有比setTimeout更好的方法来等待asnyc回调吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆