我正在尝试编写单元测试来覆盖方法 Acomplete() block 。我可以使用 Deferred 模拟 ajax 请求。但 Deferred 不支持 Complete() 所以我收到以下错误 TypeError: _this.methodB(...).complete 不是一个函数。请帮助我覆盖 methodB(..).complete() block 。
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
发出 ajax 请求。您所关心的只是它返回某个具有完整
功能的对象,以及您正确连接回调等。
测试
以下(未经测试的)代码应该大致适合您,或者为您提供一个不错的起点。
describe('.methodA()', function() {
var methodBResult;
beforeEach(function() {
methodBResult = jasmine.createSpyObj('result', ['complete']);
spyOn(f, 'methodB').and.returnValue(methodBResult);
});
it('should call .methodB()', function() {
f.refineURL = 'something for the test';
f.$el = 'something else for the test';
f.methodA();
expect(f.methodB.calls.count()).toBe(1);
expect(f.methodB).toHaveBeenCalledWith(f.refineURL, f.$el);
});
it('should register a callback on complete', function() {
f.methodA();
expect(methodBResult.complete.calls.count()).toBe(1);
expect(methodBResult.complete).toHaveBeenCalledWith(jasmine.any(Function));
});
it('should call .doSomethingOnComplete() when the callback is invoked', function() {
spyOn(f, 'doSomethingOnComplete');
f.methodA();
var callback = methodBResult.complete.calls.argsFor(1)[0];
callback();
expect(f.doSomethingOnComplete.calls.count()).toBe(1);
expect(f.doSomethingOnComplete).toHaveBeenCalledWith();
});
});
关于javascript - Jasmine Jquery Spy AJAX完整功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47027706/