【发布时间】:2018-04-12 04:01:48
【问题描述】:
我正在尝试编写单元测试来覆盖方法 A complete() 块。我可以使用 Deferred 模拟 ajax 请求。但是 Deferred 不支持 complete() 所以我遇到了错误 TypeError: _this.methodB(...).complete 不是函数。请帮我覆盖 methodB(..).complete() 块。
methodB: function(xURL, container) {
var _this = this;
return $.ajax({
type: 'GET',
url: xURL,
async: false,
dataType: 'html',
timeout: _this.ajaxTimeOut
})
.fail(function(resp) {
_this.doSomethingOnFail();
})
.done(function(resp, textStatus, jqXHR) {
if (jqXHR.status === 200 && resp !== '') {
_this.doSomethingOnDone();
}
});
},
methodA: function(e) {
var _this = this,
_this.methodB(_this.refineURL, _this.$el)
.complete(function(resp) {
**if (resp.responseText !== undefined &&
resp.responseText.indexOf("PRICE_DATA_AVLBL = 'false'") > -1) {
var params1 = _this._getFilterURLParameters(_this.refineURL);
var params2 = _this._getFilterURLParameters(_this.SUCC_URL);
if (params1.lowerbound !== params2.lowerbound ||
$(e.currentTarget).hasClass('js-txt-min')) {
$txtMin.addClass('border-danger');
} else {
$txtMin.val(params2.lowerbound);
}
} else {
_this._pageSubmit();
}**
});
}
单元测试代码:
it('validate ajax complete', function ajaxComplete(){
spyOn($, 'ajax').and.callFake( function fake() {
XMLHttpRequest = jasmine.createSpy('XMLHttpRequest');
var jqXHR = new XMLHttpRequest();
jqXHR.status = 200;
var dea = new $.Deferred();
dea.resolve('{property:value}',' ', jqXHR);
return dea;
});
f.methodA();
});
【问题讨论】:
-
如果你正在测试
methodA,你不应该担心methodB的内部结构。你应该嘲笑methodB。见我的answer。
标签: javascript jquery unit-testing jasmine jasmine-jquery