Code coverage report for src/lib/FakeTimers.js

Statements: 95.57% (151 / 158)      Branches: 92.73% (51 / 55)      Functions: 90.48% (19 / 21)      Lines: 95.57% (151 / 158)      Ignored: none     

All files » src/lib/ » FakeTimers.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351                  33   33   1 33 33 33   33     33             33                                 33   10 10         33         33 33 33 33 33 33         33           33 37 37 37 37       33       17 121   121 16     105 104 104       17 1               33 9         9 115     115 8     107     9 1               33 2 2   5           33       9 113     113 1     112 112     7 7   105 105 105       9 1             33 9       9 9 9 9 9       9   9 9 9 9   1 1     9 9 9 9 9       9 1       33 13       13 13 13 13 13 2       33 35       35 35 35 35 35 11       33 3 1       33 107 107         107 107 2 1 1         33 5 1     5 5       5   5     5           5     33 222 2     222 222 2     222   222     213           222     33 228 228 228   228 228 233 233 223 223       228     33 218   218   213 213 213 213     5 5 5             33  
/**
 * Copyright (c) 2014, Facebook, Inc. All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';
 
var mocks = require('./moduleMocker');
 
var MS_IN_A_YEAR = 31536000000;
 
function FakeTimers(global, maxLoops) {
  this._global = global;
  this._uuidCounter = 1;
  this._maxLoops = maxLoops || 100000;
 
  this.reset();
 
  // Store original timer APIs for future reference
  this._originalTimerAPIs = {
    setTimeout: global.setTimeout,
    clearTimeout: global.clearTimeout,
    setInterval: global.setInterval,
    clearInterval: global.clearInterval
  };
 
  this._fakeTimerAPIs = {
    setTimeout: mocks.getMockFn().mockImpl(
      this._fakeSetTimeout.bind(this)
    ),
    clearTimeout: mocks.getMockFn().mockImpl(
      this._fakeClearTimer.bind(this)
    ),
    setInterval: mocks.getMockFn().mockImpl(
      this._fakeSetInterval.bind(this)
    ),
    clearInterval: mocks.getMockFn().mockImpl(
      this._fakeClearTimer.bind(this)
    )
  };
 
  // If there's a process.nextTick on the global, mock it out
  // (only applicable to node/node-emulating environments)
  if (typeof global.process === 'object'
      && typeof global.process.nextTick === 'function') {
    this._originalTimerAPIs.nextTick = global.process.nextTick;
    this._fakeTimerAPIs.nextTick = mocks.getMockFn().mockImpl(
      this._fakeNextTick.bind(this)
    );
  }
 
  this.useFakeTimers();
 
  // TODO: These globally-accessible function are now deprecated!
  //       They will go away very soon, so do not use them!
  //       Instead, use the versions available on the `jest` object
  global.mockRunTicksRepeatedly = this.runAllTicks.bind(this);
  global.mockRunTimersOnce = this.runOnlyPendingTimers.bind(this);
  global.mockRunTimersToTime = this.runTimersToTime.bind(this);
  global.mockRunTimersRepeatedly = this.runAllTimers.bind(this);
  global.mockClearTimers = this.clearAllTimers.bind(this);
  global.mockGetTimersCount = function() {
    return Object.keys(this._timers).length;
  }.bind(this);
}
 
FakeTimers.prototype.clearAllTimers = function() {
  for (var uuid in this._timers) {
    delete this._timers[uuid];
  }
};
 
FakeTimers.prototype.reset = function() {
  this._cancelledTicks = {};
  this._now = 0;
  this._ticks = [];
  this._timers = {};
};
 
// Used to be called runTicksRepeatedly
FakeTimers.prototype.runAllTicks = function() {
  // Only run a generous number of ticks and then bail.
  // This is just to help avoid recursive loops
 
  for (var i = 0; i < this._maxLoops; i++) {
    var tick = this._ticks.shift();
 
    if (tick === undefined) {
      break;
    }
 
    if (!this._cancelledTicks.hasOwnProperty(tick.uuid)) {
      tick.callback();
      this._cancelledTicks[tick.uuid] = true;
    }
  }
 
  if (i === this._maxLoops) {
    throw new Error(
      'Ran ' + this._maxLoops + ' ticks, and there are still more! Assuming ' +
      'we\'ve hit an infinite recursion and bailing out...'
    );
  }
};
 
// Used to be called runTimersRepeatedly
FakeTimers.prototype.runAllTimers = function() {
  this.runAllTicks();
 
  // Only run a generous number of timers and then bail.
  // This is just to help avoid recursive loops
 
  for (var i = 0; i < this._maxLoops; i++) {
    var nextTimerHandle = this._getNextTimerHandle();
 
    // If there are no more timer handles, stop!
    if (nextTimerHandle === null) {
      break;
    }
 
    this._runTimerHandle(nextTimerHandle);
  }
 
  if (i === this._maxLoops) {
    throw new Error(
      'Ran ' + this._maxLoops + ' timers, and there are still more! Assuming ' +
      'we\'ve hit an infinite recursion and bailing out...'
    );
  }
};
 
// Used to be called runTimersOnce
FakeTimers.prototype.runOnlyPendingTimers = function() {
  var timers = this._timers;
  Object.keys(timers)
    .sort(function(left, right) {
      return timers[left].expiry - timers[right].expiry;
    })
    .forEach(this._runTimerHandle, this);
};
 
// Use to be runTimersToTime
FakeTimers.prototype.runTimersToTime = function(msToRun) {
  // Only run a generous number of timers and then bail.
  // This is jsut to help avoid recursive loops
 
  for (var i = 0; i < this._maxLoops; i++) {
    var timerHandle = this._getNextTimerHandle();
 
    // If there are no more timer handles, stop!
    if (timerHandle === null) {
      break;
    }
 
    var nextTimerExpiry = this._timers[timerHandle].expiry;
    if (this._now + msToRun < nextTimerExpiry) {
      // There are no timers between now and the target we're running to, so
      // adjust our time cursor and quit
      this._now += msToRun;
      break;
    } else {
      msToRun -= (nextTimerExpiry - this._now);
      this._now = nextTimerExpiry;
      this._runTimerHandle(timerHandle);
    }
  }
 
  if (i === this._maxLoops) {
    throw new Error(
      'Ran ' + this._maxLoops + ' timers, and there are still more! Assuming ' +
      'we\'ve hit an infinite recursion and bailing out...'
    );
  }
};
 
FakeTimers.prototype.runWithRealTimers = function(cb) {
  var hasNextTick =
    typeof this._global.process === 'object'
    && typeof this._global.process.nextTick === 'function';
 
  var prevSetTimeout = this._global.setTimeout;
  var prevSetInterval = this._global.setInterval;
  var prevClearTimeout = this._global.clearTimeout;
  var prevClearInterval = this._global.clearInterval;
  Iif (hasNextTick) {
    var prevNextTick = this._global.process.nextTick;
  }
 
  this.useRealTimers();
 
  var cbErr = null;
  var errThrown = false;
  try {
    cb();
  } catch (e) {
    errThrown = true;
    cbErr = e;
  }
 
  this._global.setTimeout = prevSetTimeout;
  this._global.setInterval = prevSetInterval;
  this._global.clearTimeout = prevClearTimeout;
  this._global.clearInterval = prevClearInterval;
  Iif (hasNextTick) {
    this._global.process.nextTick = prevNextTick;
  }
 
  if (errThrown) {
    throw cbErr;
  }
};
 
FakeTimers.prototype.useRealTimers = function() {
  var hasNextTick =
    typeof this._global.process === 'object'
    && typeof this._global.process.nextTick === 'function';
 
  this._global.setTimeout = this._originalTimerAPIs.setTimeout;
  this._global.setInterval = this._originalTimerAPIs.setInterval;
  this._global.clearTimeout = this._originalTimerAPIs.clearTimeout;
  this._global.clearInterval = this._originalTimerAPIs.clearInterval;
  if (hasNextTick) {
    this._global.process.nextTick = this._originalTimerAPIs.nextTick;
  }
};
 
FakeTimers.prototype.useFakeTimers = function() {
  var hasNextTick =
    typeof this._global.process === 'object'
    && typeof this._global.process.nextTick === 'function';
 
  this._global.setTimeout = this._fakeTimerAPIs.setTimeout;
  this._global.setInterval = this._fakeTimerAPIs.setInterval;
  this._global.clearTimeout = this._fakeTimerAPIs.clearTimeout;
  this._global.clearInterval = this._fakeTimerAPIs.clearInterval;
  if (hasNextTick) {
    this._global.process.nextTick = this._fakeTimerAPIs.nextTick;
  }
};
 
FakeTimers.prototype._fakeClearTimer = function(uuid) {
  if (this._timers.hasOwnProperty(uuid)) {
    delete this._timers[uuid];
  }
};
 
FakeTimers.prototype._fakeNextTick = function(callback) {
  var uuid = this._uuidCounter++;
  this._ticks.push({
    uuid: uuid,
    callback: callback
  });
 
  var cancelledTicks = this._cancelledTicks;
  this._originalTimerAPIs.nextTick(function() {
    if (!cancelledTicks.hasOwnProperty(uuid)) {
      callback();
      cancelledTicks[uuid] = true;
    }
  });
};
 
FakeTimers.prototype._fakeSetInterval = function(callback, intervalDelay) {
  if (intervalDelay === undefined || intervalDelay === null) {
    intervalDelay = 0;
  }
 
  var args = [];
  for (var ii = 2, ll = arguments.length; ii < ll; ii++) {
    args.push(arguments[ii]);
  }
 
  var uuid = this._uuidCounter++;
 
  this._timers[uuid] = {
    type: 'interval',
    callback: function() {
      return callback.apply(null, args);
    },
    expiry: this._now + intervalDelay,
    interval: intervalDelay
  };
 
  return uuid;
};
 
FakeTimers.prototype._fakeSetTimeout = function(callback, delay)  {
  if (delay === undefined || delay === null) {
    delay = 0;
  }
 
  var args = [];
  for (var ii = 2, ll = arguments.length; ii < ll; ii++) {
    args.push(arguments[ii]);
  }
 
  var uuid = this._uuidCounter++;
 
  this._timers[uuid] = {
    type: 'timeout',
    callback: function() {
      return callback.apply(null, args);
    },
    expiry: this._now + delay,
    interval: null
  };
 
  return uuid;
};
 
FakeTimers.prototype._getNextTimerHandle = function() {
  var nextTimerHandle = null;
  var uuid;
  var soonestTime = MS_IN_A_YEAR;
 
  var timer;
  for (uuid in this._timers) {
    timer = this._timers[uuid];
    if (timer.expiry < soonestTime) {
      soonestTime = timer.expiry;
      nextTimerHandle = uuid;
    }
  }
 
  return nextTimerHandle;
};
 
FakeTimers.prototype._runTimerHandle = function(timerHandle) {
  var timer = this._timers[timerHandle];
 
  switch (timer.type) {
    case 'timeout':
      var callback = timer.callback;
      delete this._timers[timerHandle];
      callback();
      break;
 
    case 'interval':
      timer.expiry = this._now + timer.interval;
      timer.callback();
      break;
 
    default:
      throw new Error('Unexepcted timer type: ' + timer.type);
  }
};
 
module.exports = FakeTimers;