fake-server-with-clock.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. var lolex = require("lolex");
  3. var fakeServer = require("./index");
  4. function Server() {}
  5. Server.prototype = fakeServer;
  6. var fakeServerWithClock = new Server();
  7. fakeServerWithClock.addRequest = function addRequest(xhr) {
  8. if (xhr.async) {
  9. if (typeof setTimeout.clock === "object") {
  10. this.clock = setTimeout.clock;
  11. } else {
  12. this.clock = lolex.install();
  13. this.resetClock = true;
  14. }
  15. if (!this.longestTimeout) {
  16. var clockSetTimeout = this.clock.setTimeout;
  17. var clockSetInterval = this.clock.setInterval;
  18. var server = this;
  19. this.clock.setTimeout = function (fn, timeout) {
  20. server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
  21. return clockSetTimeout.apply(this, arguments);
  22. };
  23. this.clock.setInterval = function (fn, timeout) {
  24. server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
  25. return clockSetInterval.apply(this, arguments);
  26. };
  27. }
  28. }
  29. return fakeServer.addRequest.call(this, xhr);
  30. };
  31. fakeServerWithClock.respond = function respond() {
  32. var returnVal = fakeServer.respond.apply(this, arguments);
  33. if (this.clock) {
  34. this.clock.tick(this.longestTimeout || 0);
  35. this.longestTimeout = 0;
  36. if (this.resetClock) {
  37. this.clock.uninstall();
  38. this.resetClock = false;
  39. }
  40. }
  41. return returnVal;
  42. };
  43. fakeServerWithClock.restore = function restore() {
  44. if (this.clock) {
  45. this.clock.uninstall();
  46. }
  47. return fakeServer.restore.apply(this, arguments);
  48. };
  49. module.exports = fakeServerWithClock;