【问题标题】:How to test jQuery beforeSend method with Jasmine?如何使用 Jasmine 测试 jQuery beforeSend 方法?
【发布时间】:2014-01-15 12:31:27
【问题描述】:
我找到了test promises in jasmine 的方法,但我找不到测试 beforeSend 方法的方法。
var xhr = $.ajax({
url: 'http://example.com',
type: 'POST',
data: '...',
beforeSend: function() {
methodToBeTested();
}
});
我确实需要在发送请求之前运行代码,因此不能使用 always 承诺。
【问题讨论】:
标签:
jquery
ajax
unit-testing
jasmine
【解决方案1】:
这是我觉得有点老套的解决方案,但它对我有用。
it('test beforeSend', function() {
spyOn(window, 'methodToBeTested')
spyOn($, "ajax").andCallFake(function(options) {
options.beforeSend();
expect(methodToBeTested).toHaveBeenCalled();
//this is needed if you have promise based callbacks e.g. .done(){} or .fail(){}
return new $.Deferred();
});
//call our mocked AJAX
request()
});
你也可以试试 Jasmine AJAX 插件https://github.com/pivotal/jasmine-ajax。
【解决方案2】:
你可以用这个:
if ( $.isFunction($.fn.beforeSend) ) {
//function exists
}
【解决方案3】:
或者您可以稍后访问传递给间谍 ajax 调用的参数:
$.ajax.calls.argsFor(0)[0].beforeSend();
//instead of argsFor(), you can use first(), mostRecent(), all() ...
这是在你不想每次都调用 beforeSend() 的情况下。