所以我有这样的东西:
var Utils = {};
Utils.genericAddRowPost = function(url) {
return $.post(url);
};
Utils.genericAddRow = function(dataSource, url) {
genericAddRowPost(url).done(function(data, textStatus, jqXHR) {
// add on to dataSource and other stuff
}).fail(function (jqXHR, textStatus, errorThrown) {
//handle error
});
};我正在尝试使用jasmine和毯子来测试和实现100%的代码覆盖率,但我似乎无法模拟/执行已完成和失败的处理程序。任何帮助都将不胜感激。如果可能的话,我希望不必重新构造发布的任何代码。
发布于 2013-12-16 20:31:45
我就是这样做的:
it('Verify Utils.genericAddRow', function () {
var wasSuccessful = false;
mockObj = {
data: ko.observableArray([{}])
};
// spy on genericAddRowPost that is called inside this test function
spyOn(Utils, "genericAddRowPost").andReturn({
done: function (callback) {
callback({});
wasSuccessful = true;
return this;
},
fail: function (callback) {
return this;
}
});
// Call our test function and make first set of expectations
Utils.genericAddRow(mockObj, 'fakeUrl');
expect(Utils.genericAddRowPost).toHaveBeenCalledWith('fakeUrl');
expect(wasSuccessful).toBeTruthy();
// Override original spy implementations
Utils.genericAddRowPost().done = function (callback) {
return this;
};
Utils.genericAddRowPost().fail = function(callback) {
callback(null, null, 'testError');
wasSuccessful = false;
return this;
};
// Call our test function and make second set of expectations
Utils.genericAddRow(mockObj, 'anotherFakeUrl');
expect(Utils.genericAddRowPost).toHaveBeenCalledWith('anotherFakeUrl');
expect(wasSuccessful).toBeFalsy();
});我将编辑我的问题,以反映genericAddRow和genericAddRowPost都是存在于Utils对象文本上的函数。
发布于 2013-12-14 22:28:25
使用Jasmine,您应该能够监视ajax调用,并模拟成功和失败条件。
就像这样:
describe("my tests", function () {
beforeEach(function () {
spyOn(jQuery, "ajax");
});
it("should handle success", function () {
genericAddRow(a, b);
// call the success callback
$.ajax.mostRecentCall.args[1].success(data, textStatus, jqXHR);
// do your tests here
});
it("should handle failure", function () {
genericAddRow(a, b);
// call the success callback
$.ajax.mostRecentCall.args[1].error(jqXHR, textStatus, errorThrown);
// do your tests here
});
});https://stackoverflow.com/questions/20496387
复制相似问题