这是我的代码:
function sendRequestData(url, urlParameters) {
if (url != null && urlParameters != null) {
$.ajax({
url : url,
method : 'POST',
headers : {
'Accept' : 'application/json'
},
contentType : 'application/json',
data : JSON.stringify(urlParameters),
dataType : "json",
success : function(data) {
successCallBack(data)
},
error : function(data, status, errorThrown) {
failCallBack(data, status, errorThrown)
}
});
我想存根函数并检查响应。无论如何,我可以使用jasmine-ajax插件做到这一点。
答案 0 :(得分:0)
it("should receive a successful response", function() {
spyOn($, "ajax").andCallFake(function(e) {
e.success({});
});
spyOn(window, "successCallBack");
spyOn(window, "failCallBack");
sendRequestData('dummyURL', ['dummyParam1', 'dummyParam2']);
expect(window.successCallBack).toHaveBeenCalled(); //Verifies this was called
expect(window.failCallBack).not.toHaveBeenCalled(); //Verifies this was NOT called
});
如果失败,请将callFake替换为e.error()
并撤消successCallBack
和failCallBack
有关详细信息,请参阅以下链接 http://www.htmlgoodies.com/html5/javascript/testing-ajax-event-handlers-using-jasmine-spies.html