【问题标题】:Testing ajax requests using jasmine returns TypeError使用 jasmine 测试 ajax 请求返回 TypeError
【发布时间】:2014-04-22 09:51:41
【问题描述】:

任务的描述。我想测试使用 $.get 加载资源列表的代码。

所以,源代码:

fetchTemplates: function(list, cb){
    var promises = [],
        $container = $('#templates');
    Object.keys(list).forEach(function(tplSelector){
        if($(tplSelector).length > 0){ return; }

        var promise = $.get(list[tplSelector]);
        promise
            .done(function(tplHtml){

                $container.append(tplHtml);
            })
            .fail(function(){
                console.warn('Template "' + tplSelector + " not found by url:" + list[tplSelector]);
            });

        promises.push( promise );
    });

    return $.when.apply($,promises).done(cb);
}

测试套件:

it("Correct template fetching", function (done) {
        var fetchResult = viewManager.fetchTemplates({
            '#helpTpl': 'somecorrectaddress'
        });
        fetchResult.done(function () {
            expect(true).toBeTruthy();
            done();
        });
        fetchResult.fail(function () {
            expect(false).toBeTruthy();
            done();
        });
});

它产生了什么。测试通过,但产生错误: TypeError:'null' 不是对象(评估 'this.results_.addResult') 在 jasmine.js?2348

因此,测试用例标记为通过。但是整个测试套件仍然会产生上述错误(并且此方法是唯一的异步方法,其他部分测试起来很简单)。我的想法是,由于测试的方法包含异步操作和承诺 - 结果没有正确处理,因此出现 TypeError。所以我添加了 jasmine async "done()" 来处理这个问题——不幸的是没有任何改变。另外值得注意的是,如果我使用“iit”在套件中只留下一个测试 - 不会产生错误。搜索没有找到类似的案例。有什么想法吗?

【问题讨论】:

    标签: javascript ajax unit-testing jasmine jquery-deferred


    【解决方案1】:

    之后,您需要使用“waitsFor()”将异步调用包装在“runs()”中,阅读文档here。我从来没有使用过 jquery,但是在你的 it 函数中尝试如下操作:

    var done = false;
    var that = this;
    
    runs( function() {
        //your async test goes here
        that.done = true;
    });
    
    waitsFor( function() {
        return that.done;
    }, "async code failed", 2000);
    

    【讨论】:

      猜你喜欢
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      相关资源
      最近更新 更多