或Sinon正确地测试jQuery的

或Sinon正确地测试jQuery的

本文介绍了如何使用Jasmine和/或Sinon正确地测试jQuery的.ajax()承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当简单的函数,它返回一个jQuery .ajax()承诺:

I've got a fairly straightforward function which returns a jQuery .ajax() promise as such:

CLAW.controls.validateLocation = function(val, $inputEl) {
    return $.ajax({
        url: locationServiceUrl + 'ValidateLocation/',
        data: {
            'locationName': val
        },
        beforeSend: function() {
            $inputEl.addClass('busy');
        }
    }).done(function(result) {
        // some success clauses
    }).fail(function(result) {
        // some failure clauses
    }).always(function() {
        // some always clauses
    });
}

在大多数情况下,这个新的promises界面就像一个梦想,并消除使用jQuery的.ajax()时回调金字塔很棒。但是,我不能为我的生活弄清楚如何使用Jasmine和/或Sinon正确测试这些承诺:

For the most part, this new promises interface works like a dream, and eliminating callback pyramids when using jQuery's .ajax() is great. However, I cannot for the life of me figure out how to properly test these promises using Jasmine and/or Sinon:


  1. 全部Sinon的文档假设您使用的是旧式的
    回调;我没有看到如何使用
    promises / deferreds的单一示例

  1. All of Sinon's documentation assumes you're using old-schoolcallbacks; I don't see a single example of how to use it withpromises/deferreds

当试图使用Jasmine或Sinon间谍进行侦察时在$ .ajax上,
间谍有效地覆盖了承诺,因此其已完成失败
始终条款不再存在于ajax函数中,因此承诺永远不会解决并抛出错误

When attempting to use a Jasmine or Sinon spy to spy on $.ajax, thespy is effectively overwriting the promise, so its done, fail,and always clauses no longer exist on the ajax function, so the promise never resolves and tosses an error instead

我真的很喜欢如何使用上述测试库测试这些新的jQuery .ajax()承诺的一两个例子。我已经相当强烈地搜索了网络,并没有真正挖掘任何东西。我找到的一个资源是使用Jasmine.ajax提到的,但我想尽可能避免这种情况,因为Sinon提供了大部分开箱即用的相同功能。

I'd really just love an example or two of how to test these new jQuery .ajax() promises with the aforementioned testing libs. I've scoured the 'net fairly intensely and haven't really dredged up anything on doing so. The one resource I did find mentioned using Jasmine.ajax, but I'd like to avoid that if possible, seeing as Sinon provides most of the same capabilities out-of-the-box.

推荐答案

实际上并不复杂。回报承诺并根据您的情况解决它就足够了。

It is not that complex actually. It suffices to return a promise and resolve it according to your case.

例如:

spyOn($, 'ajax').andCallFake(function (req) {
    var d = $.Deferred();
    d.resolve(data_you_expect);
    return d.promise();
});

成功,或

spyOn($, 'ajax').andCallFake(function (req) {
    var d = $.Deferred();
    d.reject(fail_result);
    return d.promise();
});

失败。

对于Jasmine 2.0语法略有改变:

For Jasmine 2.0 the syntax has changed slightly:

spyOn($, 'ajax').and.callFake(function (req) {});

方法.andCallFake()在Jasmine 2.0中不存在

the method .andCallFake() does not exist in Jasmine 2.0

这篇关于如何使用Jasmine和/或Sinon正确地测试jQuery的.ajax()承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:56