Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sinon.FakeXMLHttpRequest = (function () {
// ...
function FakeXMLHttpRequest() {
this.readyState = FakeXMLHttpRequest.UNSENT;
this.requestHeaders = {};
this.requestBody = null;
this.status = 0;
this.statusText = "";
this.eventListeners = {};
if (typeof FakeXMLHttpRequest.onCreate == "function") {
FakeXMLHttpRequest.onCreate(this);
}
}
var Event = function Event() {};
sinon.extend(Event.prototype, {
initEvent: function(type, bubbles, cancelable) {
this.type = type;
this.bubbles = bubbles;
this.cancelable = cancelable;
},
stopPropagation: function() {
},
preventDefault: function() {
}
});
// ...
sinon.extend(FakeXMLHttpRequest.prototype, {
// ...
addEventListener: function addEventListener(event, listener, useCapture) {
var listeners = this.eventListeners[event];
if(!listeners){
listeners = this.eventListeners[event] = [];
}
listeners.push(listener);
},
removeEventListener: function removeEventListener(event, listener, useCapture) {
var listeners = this.eventListeners[event];
if(listeners) {
var index = listeners.indexOf(listener);
if(index != -1) {
listeners.splice(index, 1);
}
}
},
dispatchEvent: function dispatchEvent(event) {
var listeners = this.eventListeners[event.type];
if(listeners) {
for(var i = 0; i < listeners.length; i++) {
listeners[i](event); // TODO shouldn't this implement handleEvent() ?
}
}
},
readyStateChange: function readyStateChange(state) {
this.readyState = state;
if (typeof this.onreadystatechange == "function") {
this.onreadystatechange();
}
var event = new Event();
event.initEvent('readystatechange');
this.dispatchEvent(event);
},
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment