Add Dygraph.ready() method to simplify annotations usage.
[dygraphs.git] / auto_tests / tests / Util.js
index 2d652ed..8a14e06 100644 (file)
@@ -95,3 +95,39 @@ Util.samplePixel = function(canvas, x, y) {
   var d = imageData.data;
   return [d[i], d[i+1], d[i+2], d[i+3]];
 };
+
+/**
+ * Overrides the browser's built-in XMLHttpRequest with a mock.
+ * Usage:
+ *
+ * var mockXhr = Util.overrideXMLHttpRequest(your_data);
+ * ... call code that does an XHR ...
+ * mockXhr.respond();  // restores default behavior.
+ * ... do your assertions ...
+ */
+Util.overrideXMLHttpRequest = function(data) {
+  var originalXMLHttpRequest = XMLHttpRequest;
+
+  var requests = [];
+  var FakeXMLHttpRequest = function () {
+    requests.push(this);
+  };
+  FakeXMLHttpRequest.prototype.open = function () {};
+  FakeXMLHttpRequest.prototype.send = function () {
+    this.readyState = 4;
+    this.status = 200;
+    this.responseText = data;
+  };
+  FakeXMLHttpRequest.restore = function() {
+    XMLHttpRequest = originalXMLHttpRequest;
+  };
+  FakeXMLHttpRequest.respond = function() {
+    for (var i = 0; i < requests.length; i++) {
+      requests[i].onreadystatechange();
+    }
+    FakeXMLHttpRequest.restore();
+  };
+  XMLHttpRequest = FakeXMLHttpRequest;
+  return FakeXMLHttpRequest;
+};
+