I'm using js-test-driver and inside i use jasmine for testing and sinon for spies, fakeXMLHttpRequests and so on..
Let's assume we load the following files:
load:
- lib/jasmine.js
- lib/JasmineAdapter.js
- lib/sinon.js
- lib/jquery-1.8.3.min.js
- spec/*.js
Inside the spec folder is a file test.js with the following content:
describe('test', function() {
it('should use sinon fakeXMLHttpRequest', function() {
var result = [],
requests = [];
this.callback = function(xhr, textStatus) {
result = textStatus;
}
var callbackSpy = sinon.spy(this, 'callback');
var xhr = sinon.useFakeXMLHttpRequest();
var clock = sinon.useFakeTimers();
xhr.onCreate = function(xhr) {
requests.push(xhr);
}
expect(requests.length).toBe(0);
expect(callbackSpy.called).toBeFalsy();
jQuery.ajax({
async: false,
url: 'somevalidurl.php',
complete: this.callback
});
expect(requests.length).toBe(1);
requests[0].respond(200, { "Content-Type": "application/json" },
'[{ "id": 12, "text": "Something" }]');
clock.tick(2000);
expect(callbackSpy.called).toBeTruthy();
expect(result).toBe('success')
xhr.restore();
});
});
Then we get the following errors:
Error: Expected false to be truthy.
Error: Expected [ ] to be 'success'.
If we change to "async: true" everything works fine. Is this a bug or is there some behaviour I'm missing?
sorry, my fault. for those who have the same problem:
Of course it does not work. Cause a synchronous XMLHttpRequest stops the execution. Sinon's fakeXMLHttpRequest is doing something strange in this case. So I have refactored my tested code to use asynchronous http requests.