Jasmine 2.0如何处理ajax请求 [英] Jasmine 2.0 how to handle ajax requests
问题描述
我想测试一个包含ajax请求的函数。测试应该等待ajax-request成功/失败。运行测试不起作用,因为它现在不会等待。
I want to test a function, that includes a ajax request. The test should wait for the ajax-request to success/fail. Running the test doesn't work, because it doesn't wait right now.
这个我想要测试:
this.requestServerBoxId = function()
{
//ajax-request
$.ajax({
url: this.host_addr+"/?getid="+this.name,
type: 'POST',
data: {_data:this._data},
success: function(data) {
return IdSuccess(data);
},
error: function(data){
return false;
}
});
}
function IdSuccess(data){
if(typeof data != undefined)
return true;
return false;
}
这是我的测试:
it("should call a function after ajax-success", function(){
expect(this.Process.requestServerBoxId()).toBe(true);
});
我试过间谍,但我猜我错了:
I tried out spies, but I guess I'm using them wrong:
spyOn($, 'ajax' ).and.returnValue(123);
我希望这个间谍每次发出ajax请求时都会返回123。但它不起作用。
I was hoping that this spy return 123 every time a ajax request is beeing made. But it doesn't work.
推荐答案
使用Jasmine 2.0,有一个全新的API来测试ajax(几乎所有的东西)否则)。
With Jasmine 2.0, there is a completely new API for testing ajax (and just about everything else).
而不是:
spyOn($, 'ajax').and.returnValue(123);
设置 beforeEach
和 afterEach
方法之前
测试:
beforeEach(function() {
jasmine.Ajax.install();
jasmine.Ajax.stubRequest('YOUR_URL_HERE').andReturn({
responseText: 'YOUR_RAW_STUBBED_DATA_HERE'
});
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
it('My Ajax Test', function() {
// . . . code that makes an ajax request . . .
});
it
测试将执行其ajax按预期请求。
The it
test will then execute its ajax request as expected.
请注意,这会使您的ajax调用基本上同步但是立即执行。
Note that this makes your ajax call essentially synchronous but immediate.
这篇关于Jasmine 2.0如何处理ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!