我有一个触发ajax请求的Jasmine 2.0.2测试,但每次触发请求时,模拟ajax返回应该是一个特定的返回值。
var setUpDeleteEventInAjax = function(spyEvent, idToReturn){
var spy;
spy = jasmine.createSpy('ajax');
spyAjaxEvent = spyOnEvent(spyEvent, 'click');
spyOn($, 'ajax').and.callFake(function (param) {
return {
id: idToReturn, // here I am trying to return a defined value
status: true
};
});
spyAjaxEvent.reset(); // this should reset all ajax evetns
};
...
beforeEach(function(){...})
afterEach(function(){...})
...
it('Deleting all the addresses should reveal the form', function () {
setUpDeleteEventInAjax('#delete',52670);
$('#delete').click();
expect($('.address-item').length).toEqual(4);
setUpDeleteEventInAjax('#delete-2',52671);
$('#delete-2').click();
expect($('.address-item').length).toEqual(2);
setUpDeleteEventInAjax('#delete-3',52672);
$('#delete-3').click();
expect($('.address-item').length).toEqual(0);
});
...
单击删除按钮(删除,删除-2,删除-3)后,总长度地址项减少2(当服务器返回时,数字响应 - 这是模拟的关键)。
然而,茉莉抱怨说“阿贾克斯已经被监视过了”。有没有办法从ajax mock中返回一个新值才能完成测试?
答案 0 :(得分:1)
实际上,我采用的方式是过度设计的。只是需要关闭。不需要我的自定义setUpDeleteEventInAjax
功能
it('Deleting all the addresses should reveal the form', function () {
var responses = [52670, 52671, 52672];
var ajaxResponses = function () {
return {
status: true,
id: responses.shift()
}
};
spyOn($, 'ajax').and.callFake(ajaxResponses);
$('#delete').click();
expect($('.address-item').length).toEqual(4);
$('#delete-2').click();
expect($('.address-item').length).toEqual(2);
expect($('.address-book')).toHaveClass('single-address');
$('#delete-3').click();
expect($('.address-item').length).toEqual(0);
});