使javascript函数callback-ish [英] make javascript function callback-ish

查看:55
本文介绍了使javascript函数callback-ish的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery使用javascript函数:

i'm having a javascript function using jquery:

my.namespace.loadSomeStuff = function() {

    $.get('/Services/loadStuff', function(c){
        $("#stuffDiv").html(c);
    });
};

并且正在尝试为此编写单元测试.

and am trying to write unit tests for this.

现在,由于此函数并未真正返回任何内容并正在加载 使用jquery的"get"异步操作的一些东西,我很难测试这一点.

now, since this function is not really returning anything and loading some stuff asynchronous using jquery's 'get' i'm having a hard time testing this.

基本上我想做的就是调用此函数,等到它 返回内容,然后访问已加载的元素以进行验证... 像这样:

essentially what i would like to do is call this function, wait until it returns something and then access the loaded elements to verify... something like:

my.namespace.loadSomeStuff(function(){
    alert('boo');
    assertSame('Login', $("#stuffDiv").find(......);
});

现在,我在模板中创建了一个调用单元测试的模板, 它将正确加载并显示,但是警报或断言将永远不会执行.

now, i created a in the template that calls the unit test, and it will load and display correctly, but the alert or the assert are never executed.

有没有一种方法可以在不向我拥有的每个函数中添加大量额外代码的情况下做到这一点?

is there a way i can do this without adding a ton of extra code to every single function i have?

谢谢 t

推荐答案

您必须在loadSomeStuff方法中添加一个参数,以接收您在示例代码中调用的回调函数,然后有意对其进行调用:

You'd have to add an argument to the loadSomeStuff method to receive the callback function you called in your example code, and then deliberately call it:

my.namespace.loadSomeStuff= function(callback) {
    $.get('/Services/loadStuff', function(c){
        $("#stuffDiv").html(c);
        if (callback!==undefined)
            callback();
    });
};

我不确定仅仅为了支持单元测试而使代码更复杂是值得的,尽管您可能会争辩说将回调添加到异步函数具有通用性.

I'm not sure it's worth making your code more complicated merely to support unit tests, though you could argue that adding callbacks to async functions is of general-purpose usefulness.

另一种选择是使测试使用粗略的超时.

An alternative would be making the test use a crude timeout.

您可以使用Nick提到的ajaxSuccess(可能与超时结合使用,并且/或者还捕获了ajaxError?).但是令我惊讶的是,这可能为单元测试增加了太多的实现知识.如果将来将loadSomeStuff更改为在没有XMLHttpRequest的情况下可以工作,或者可能仅在不缓存时使用它,该怎么办?然后,单元测试将中断.当然,您可以更新测试以匹配实现,但这并不是真正有用的单元测试,是吗?

You could use ajaxSuccess as mentioned by Nick (maybe combined with a timeout, and/or also catching ajaxError?). But it strikes me this might be adding a bit too much implementation knowledge for a unit test. What if loadSomeStuff is changed in future to work without an XMLHttpRequest, or maybe only use it sometimes, when it's not cached? Then the unit test will break. Sure, you can update the test to match the implementation, but then that's not really a useful unit test, is it?

这篇关于使javascript函数callback-ish的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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