lolex.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.lolex = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. (function (global){
  3. "use strict";
  4. function withGlobal(_global) {
  5. var userAgent = _global.navigator && _global.navigator.userAgent;
  6. var isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1;
  7. var maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
  8. // Make properties writable in IE, as per
  9. // http://www.adequatelygood.com/Replacing-setTimeout-Globally.html
  10. if (isRunningInIE) {
  11. _global.setTimeout = _global.setTimeout;
  12. _global.clearTimeout = _global.clearTimeout;
  13. _global.setInterval = _global.setInterval;
  14. _global.clearInterval = _global.clearInterval;
  15. _global.Date = _global.Date;
  16. }
  17. // setImmediate is not a standard function
  18. // avoid adding the prop to the window object if not present
  19. if (_global.setImmediate !== undefined) {
  20. _global.setImmediate = _global.setImmediate;
  21. _global.clearImmediate = _global.clearImmediate;
  22. }
  23. // node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref()
  24. // browsers, a number.
  25. // see https://github.com/cjohansen/Sinon.JS/pull/436
  26. var NOOP = function () { return undefined; };
  27. var timeoutResult = _global.setTimeout(NOOP, 0);
  28. var addTimerReturnsObject = typeof timeoutResult === "object";
  29. var hrtimePresent = (_global.process && typeof _global.process.hrtime === "function");
  30. var nextTickPresent = (_global.process && typeof _global.process.nextTick === "function");
  31. var performancePresent = (_global.performance && typeof _global.performance.now === "function");
  32. var hasPerformancePrototype = (_global.Performance && (typeof _global.Performance).match(/^(function|object)$/));
  33. var queueMicrotaskPresent = (typeof _global.queueMicrotask === "function");
  34. var requestAnimationFramePresent = (
  35. _global.requestAnimationFrame && typeof _global.requestAnimationFrame === "function"
  36. );
  37. var cancelAnimationFramePresent = (
  38. _global.cancelAnimationFrame && typeof _global.cancelAnimationFrame === "function"
  39. );
  40. var requestIdleCallbackPresent = (
  41. _global.requestIdleCallback && typeof _global.requestIdleCallback === "function"
  42. );
  43. var cancelIdleCallbackPresent = (
  44. _global.cancelIdleCallback && typeof _global.cancelIdleCallback === "function"
  45. );
  46. _global.clearTimeout(timeoutResult);
  47. var NativeDate = _global.Date;
  48. var uniqueTimerId = 1;
  49. function isNumberFinite(num) {
  50. if (Number.isFinite) {
  51. return Number.isFinite(num);
  52. }
  53. if (typeof num !== "number") {
  54. return false;
  55. }
  56. return isFinite(num);
  57. }
  58. /**
  59. * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
  60. * number of milliseconds. This is used to support human-readable strings passed
  61. * to clock.tick()
  62. */
  63. function parseTime(str) {
  64. if (!str) {
  65. return 0;
  66. }
  67. var strings = str.split(":");
  68. var l = strings.length;
  69. var i = l;
  70. var ms = 0;
  71. var parsed;
  72. if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
  73. throw new Error("tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits");
  74. }
  75. while (i--) {
  76. parsed = parseInt(strings[i], 10);
  77. if (parsed >= 60) {
  78. throw new Error("Invalid time " + str);
  79. }
  80. ms += parsed * Math.pow(60, (l - i - 1));
  81. }
  82. return ms * 1000;
  83. }
  84. /**
  85. * Get the decimal part of the millisecond value as nanoseconds
  86. *
  87. * @param {Number} msFloat the number of milliseconds
  88. * @returns {Number} an integer number of nanoseconds in the range [0,1e6)
  89. *
  90. * Example: nanoRemainer(123.456789) -> 456789
  91. */
  92. function nanoRemainder(msFloat) {
  93. var modulo = 1e6;
  94. var remainder = (msFloat * 1e6) % modulo;
  95. var positiveRemainder = remainder < 0 ? remainder + modulo : remainder;
  96. return Math.floor(positiveRemainder);
  97. }
  98. /**
  99. * Used to grok the `now` parameter to createClock.
  100. * @param epoch {Date|number} the system time
  101. */
  102. function getEpoch(epoch) {
  103. if (!epoch) { return 0; }
  104. if (typeof epoch.getTime === "function") { return epoch.getTime(); }
  105. if (typeof epoch === "number") { return epoch; }
  106. throw new TypeError("now should be milliseconds since UNIX epoch");
  107. }
  108. function inRange(from, to, timer) {
  109. return timer && timer.callAt >= from && timer.callAt <= to;
  110. }
  111. function mirrorDateProperties(target, source) {
  112. var prop;
  113. for (prop in source) {
  114. if (source.hasOwnProperty(prop)) {
  115. target[prop] = source[prop];
  116. }
  117. }
  118. // set special now implementation
  119. if (source.now) {
  120. target.now = function now() {
  121. return target.clock.now;
  122. };
  123. } else {
  124. delete target.now;
  125. }
  126. // set special toSource implementation
  127. if (source.toSource) {
  128. target.toSource = function toSource() {
  129. return source.toSource();
  130. };
  131. } else {
  132. delete target.toSource;
  133. }
  134. // set special toString implementation
  135. target.toString = function toString() {
  136. return source.toString();
  137. };
  138. target.prototype = source.prototype;
  139. target.parse = source.parse;
  140. target.UTC = source.UTC;
  141. target.prototype.toUTCString = source.prototype.toUTCString;
  142. return target;
  143. }
  144. function createDate() {
  145. function ClockDate(year, month, date, hour, minute, second, ms) {
  146. // Defensive and verbose to avoid potential harm in passing
  147. // explicit undefined when user does not pass argument
  148. switch (arguments.length) {
  149. case 0:
  150. return new NativeDate(ClockDate.clock.now);
  151. case 1:
  152. return new NativeDate(year);
  153. case 2:
  154. return new NativeDate(year, month);
  155. case 3:
  156. return new NativeDate(year, month, date);
  157. case 4:
  158. return new NativeDate(year, month, date, hour);
  159. case 5:
  160. return new NativeDate(year, month, date, hour, minute);
  161. case 6:
  162. return new NativeDate(year, month, date, hour, minute, second);
  163. default:
  164. return new NativeDate(year, month, date, hour, minute, second, ms);
  165. }
  166. }
  167. return mirrorDateProperties(ClockDate, NativeDate);
  168. }
  169. function enqueueJob(clock, job) {
  170. // enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
  171. if (!clock.jobs) {
  172. clock.jobs = [];
  173. }
  174. clock.jobs.push(job);
  175. }
  176. function runJobs(clock) {
  177. // runs all microtick-deferred tasks - ecma262/#sec-runjobs
  178. if (!clock.jobs) {
  179. return;
  180. }
  181. for (var i = 0; i < clock.jobs.length; i++) {
  182. var job = clock.jobs[i];
  183. job.func.apply(null, job.args);
  184. if (clock.loopLimit && i > clock.loopLimit) {
  185. throw new Error("Aborting after running " + clock.loopLimit + " timers, assuming an infinite loop!");
  186. }
  187. }
  188. clock.jobs = [];
  189. }
  190. function addTimer(clock, timer) {
  191. if (timer.func === undefined) {
  192. throw new Error("Callback must be provided to timer calls");
  193. }
  194. timer.type = timer.immediate ? "Immediate" : "Timeout";
  195. if (timer.hasOwnProperty("delay")) {
  196. if (!isNumberFinite(timer.delay)) {
  197. timer.delay = 0;
  198. }
  199. timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
  200. timer.delay = Math.max(0, timer.delay);
  201. }
  202. if (timer.hasOwnProperty("interval")) {
  203. timer.type = "Interval";
  204. timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
  205. }
  206. if (timer.hasOwnProperty("animation")) {
  207. timer.type = "AnimationFrame";
  208. timer.animation = true;
  209. }
  210. if (!clock.timers) {
  211. clock.timers = {};
  212. }
  213. timer.id = uniqueTimerId++;
  214. timer.createdAt = clock.now;
  215. timer.callAt = clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
  216. clock.timers[timer.id] = timer;
  217. if (addTimerReturnsObject) {
  218. var res = {
  219. id: timer.id,
  220. ref: function () { return res; },
  221. unref: function () { return res; },
  222. refresh: function () { return res; }
  223. };
  224. return res;
  225. }
  226. return timer.id;
  227. }
  228. /* eslint consistent-return: "off" */
  229. function compareTimers(a, b) {
  230. // Sort first by absolute timing
  231. if (a.callAt < b.callAt) {
  232. return -1;
  233. }
  234. if (a.callAt > b.callAt) {
  235. return 1;
  236. }
  237. // Sort next by immediate, immediate timers take precedence
  238. if (a.immediate && !b.immediate) {
  239. return -1;
  240. }
  241. if (!a.immediate && b.immediate) {
  242. return 1;
  243. }
  244. // Sort next by creation time, earlier-created timers take precedence
  245. if (a.createdAt < b.createdAt) {
  246. return -1;
  247. }
  248. if (a.createdAt > b.createdAt) {
  249. return 1;
  250. }
  251. // Sort next by id, lower-id timers take precedence
  252. if (a.id < b.id) {
  253. return -1;
  254. }
  255. if (a.id > b.id) {
  256. return 1;
  257. }
  258. // As timer ids are unique, no fallback `0` is necessary
  259. }
  260. function firstTimerInRange(clock, from, to) {
  261. var timers = clock.timers;
  262. var timer = null;
  263. var id, isInRange;
  264. for (id in timers) {
  265. if (timers.hasOwnProperty(id)) {
  266. isInRange = inRange(from, to, timers[id]);
  267. if (isInRange && (!timer || compareTimers(timer, timers[id]) === 1)) {
  268. timer = timers[id];
  269. }
  270. }
  271. }
  272. return timer;
  273. }
  274. function firstTimer(clock) {
  275. var timers = clock.timers;
  276. var timer = null;
  277. var id;
  278. for (id in timers) {
  279. if (timers.hasOwnProperty(id)) {
  280. if (!timer || compareTimers(timer, timers[id]) === 1) {
  281. timer = timers[id];
  282. }
  283. }
  284. }
  285. return timer;
  286. }
  287. function lastTimer(clock) {
  288. var timers = clock.timers;
  289. var timer = null;
  290. var id;
  291. for (id in timers) {
  292. if (timers.hasOwnProperty(id)) {
  293. if (!timer || compareTimers(timer, timers[id]) === -1) {
  294. timer = timers[id];
  295. }
  296. }
  297. }
  298. return timer;
  299. }
  300. function callTimer(clock, timer) {
  301. if (typeof timer.interval === "number") {
  302. clock.timers[timer.id].callAt += timer.interval;
  303. } else {
  304. delete clock.timers[timer.id];
  305. }
  306. if (typeof timer.func === "function") {
  307. timer.func.apply(null, timer.args);
  308. } else {
  309. /* eslint no-eval: "off" */
  310. eval(timer.func);
  311. }
  312. }
  313. function clearTimer(clock, timerId, ttype) {
  314. if (!timerId) {
  315. // null appears to be allowed in most browsers, and appears to be
  316. // relied upon by some libraries, like Bootstrap carousel
  317. return;
  318. }
  319. if (!clock.timers) {
  320. clock.timers = {};
  321. }
  322. // in Node, timerId is an object with .ref()/.unref(), and
  323. // its .id field is the actual timer id.
  324. if (typeof timerId === "object") {
  325. timerId = timerId.id;
  326. }
  327. if (clock.timers.hasOwnProperty(timerId)) {
  328. // check that the ID matches a timer of the correct type
  329. var timer = clock.timers[timerId];
  330. if (timer.type === ttype) {
  331. delete clock.timers[timerId];
  332. } else {
  333. var clear = ttype === "AnimationFrame" ? "cancelAnimationFrame" : "clear" + ttype;
  334. var schedule = timer.type === "AnimationFrame" ? "requestAnimationFrame" : "set" + timer.type;
  335. throw new Error("Cannot clear timer: timer created with " + schedule
  336. + "() but cleared with " + clear + "()");
  337. }
  338. }
  339. }
  340. function uninstall(clock, target, config) {
  341. var method,
  342. i,
  343. l;
  344. var installedHrTime = "_hrtime";
  345. var installedNextTick = "_nextTick";
  346. for (i = 0, l = clock.methods.length; i < l; i++) {
  347. method = clock.methods[i];
  348. if (method === "hrtime" && target.process) {
  349. target.process.hrtime = clock[installedHrTime];
  350. } else if (method === "nextTick" && target.process) {
  351. target.process.nextTick = clock[installedNextTick];
  352. } else if (method === "performance") {
  353. target[method] = clock["_" + method];
  354. } else {
  355. if (target[method] && target[method].hadOwnProperty) {
  356. target[method] = clock["_" + method];
  357. if (method === "clearInterval" && config.shouldAdvanceTime === true) {
  358. target[method](clock.attachedInterval);
  359. }
  360. } else {
  361. try {
  362. delete target[method];
  363. } catch (ignore) { /* eslint empty-block: "off" */ }
  364. }
  365. }
  366. }
  367. // Prevent multiple executions which will completely remove these props
  368. clock.methods = [];
  369. // return pending timers, to enable checking what timers remained on uninstall
  370. if (!clock.timers) {
  371. return [];
  372. }
  373. return Object.keys(clock.timers).map(function mapper(key) {
  374. return clock.timers[key];
  375. });
  376. }
  377. function hijackMethod(target, method, clock) {
  378. var prop;
  379. clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method);
  380. clock["_" + method] = target[method];
  381. if (method === "Date") {
  382. var date = mirrorDateProperties(clock[method], target[method]);
  383. target[method] = date;
  384. } else if (method === "performance") {
  385. target[method] = clock[method];
  386. } else {
  387. target[method] = function () {
  388. return clock[method].apply(clock, arguments);
  389. };
  390. for (prop in clock[method]) {
  391. if (clock[method].hasOwnProperty(prop)) {
  392. target[method][prop] = clock[method][prop];
  393. }
  394. }
  395. }
  396. target[method].clock = clock;
  397. }
  398. function doIntervalTick(clock, advanceTimeDelta) {
  399. clock.tick(advanceTimeDelta);
  400. }
  401. var timers = {
  402. setTimeout: _global.setTimeout,
  403. clearTimeout: _global.clearTimeout,
  404. setImmediate: _global.setImmediate,
  405. clearImmediate: _global.clearImmediate,
  406. setInterval: _global.setInterval,
  407. clearInterval: _global.clearInterval,
  408. Date: _global.Date
  409. };
  410. if (hrtimePresent) {
  411. timers.hrtime = _global.process.hrtime;
  412. }
  413. if (nextTickPresent) {
  414. timers.nextTick = _global.process.nextTick;
  415. }
  416. if (performancePresent) {
  417. timers.performance = _global.performance;
  418. }
  419. if (requestAnimationFramePresent) {
  420. timers.requestAnimationFrame = _global.requestAnimationFrame;
  421. }
  422. if (queueMicrotaskPresent) {
  423. timers.queueMicrotask = _global.queueMicrotask;
  424. }
  425. if (cancelAnimationFramePresent) {
  426. timers.cancelAnimationFrame = _global.cancelAnimationFrame;
  427. }
  428. if (requestIdleCallbackPresent) {
  429. timers.requestIdleCallback = _global.requestIdleCallback;
  430. }
  431. if (cancelIdleCallbackPresent) {
  432. timers.cancelIdleCallback = _global.cancelIdleCallback;
  433. }
  434. var keys = Object.keys || function (obj) {
  435. var ks = [];
  436. var key;
  437. for (key in obj) {
  438. if (obj.hasOwnProperty(key)) {
  439. ks.push(key);
  440. }
  441. }
  442. return ks;
  443. };
  444. /**
  445. * @param start {Date|number} the system time - non-integer values are floored
  446. * @param loopLimit {number} maximum number of timers that will be run when calling runAll()
  447. */
  448. function createClock(start, loopLimit) {
  449. start = Math.floor(getEpoch(start));
  450. loopLimit = loopLimit || 1000;
  451. var nanos = 0;
  452. var adjustedSystemTime = [0, 0]; // [millis, nanoremainder]
  453. if (NativeDate === undefined) {
  454. throw new Error("The global scope doesn't have a `Date` object"
  455. + " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)");
  456. }
  457. var clock = {
  458. now: start,
  459. timeouts: {},
  460. Date: createDate(),
  461. loopLimit: loopLimit
  462. };
  463. clock.Date.clock = clock;
  464. function getTimeToNextFrame() {
  465. return 16 - ((clock.now - start) % 16);
  466. }
  467. function hrtime(prev) {
  468. var millisSinceStart = clock.now - adjustedSystemTime[0] - start;
  469. var secsSinceStart = Math.floor( millisSinceStart / 1000);
  470. var remainderInNanos = (millisSinceStart - secsSinceStart * 1e3 ) * 1e6 + nanos - adjustedSystemTime[1];
  471. if (Array.isArray(prev)) {
  472. if ( prev[1] > 1e9 ) {
  473. throw new TypeError("Number of nanoseconds can't exceed a billion");
  474. }
  475. var oldSecs = prev[0];
  476. var nanoDiff = remainderInNanos - prev[1];
  477. var secDiff = secsSinceStart - oldSecs;
  478. if (nanoDiff < 0) {
  479. nanoDiff += 1e9;
  480. secDiff -= 1;
  481. }
  482. return [secDiff, nanoDiff];
  483. }
  484. return [secsSinceStart, remainderInNanos];
  485. }
  486. clock.requestIdleCallback = function requestIdleCallback(func, timeout) {
  487. var timeToNextIdlePeriod = 0;
  488. if (clock.countTimers() > 0) {
  489. timeToNextIdlePeriod = 50; // const for now
  490. }
  491. var result = addTimer(clock, {
  492. func: func,
  493. args: Array.prototype.slice.call(arguments, 2),
  494. delay: typeof timeout === "undefined" ? timeToNextIdlePeriod : Math.min(timeout, timeToNextIdlePeriod)
  495. });
  496. return result.id || result;
  497. };
  498. clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
  499. return clearTimer(clock, timerId, "Timeout");
  500. };
  501. clock.setTimeout = function setTimeout(func, timeout) {
  502. return addTimer(clock, {
  503. func: func,
  504. args: Array.prototype.slice.call(arguments, 2),
  505. delay: timeout
  506. });
  507. };
  508. clock.clearTimeout = function clearTimeout(timerId) {
  509. return clearTimer(clock, timerId, "Timeout");
  510. };
  511. clock.nextTick = function nextTick(func) {
  512. return enqueueJob(clock, {
  513. func: func,
  514. args: Array.prototype.slice.call(arguments, 1)
  515. });
  516. };
  517. clock.queueMicrotask = function queueMicrotask(func) {
  518. return clock.nextTick(func); // explicitly drop additional arguments
  519. };
  520. clock.setInterval = function setInterval(func, timeout) {
  521. timeout = parseInt(timeout, 10);
  522. return addTimer(clock, {
  523. func: func,
  524. args: Array.prototype.slice.call(arguments, 2),
  525. delay: timeout,
  526. interval: timeout
  527. });
  528. };
  529. clock.clearInterval = function clearInterval(timerId) {
  530. return clearTimer(clock, timerId, "Interval");
  531. };
  532. clock.setImmediate = function setImmediate(func) {
  533. return addTimer(clock, {
  534. func: func,
  535. args: Array.prototype.slice.call(arguments, 1),
  536. immediate: true
  537. });
  538. };
  539. clock.clearImmediate = function clearImmediate(timerId) {
  540. return clearTimer(clock, timerId, "Immediate");
  541. };
  542. clock.countTimers = function countTimers() {
  543. return Object.keys(clock.timers || {}).length;
  544. };
  545. clock.requestAnimationFrame = function requestAnimationFrame(func) {
  546. var result = addTimer(clock, {
  547. func: func,
  548. delay: getTimeToNextFrame(),
  549. args: [clock.now + getTimeToNextFrame()],
  550. animation: true
  551. });
  552. return result.id || result;
  553. };
  554. clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
  555. return clearTimer(clock, timerId, "AnimationFrame");
  556. };
  557. clock.runMicrotasks = function runMicrotasks() {
  558. runJobs(clock);
  559. };
  560. /**
  561. * @param {tickValue} {String|Number} number of milliseconds or a human-readable value like "01:11:15"
  562. */
  563. clock.tick = function tick(tickValue) {
  564. var msFloat = typeof tickValue === "number" ? tickValue : parseTime(tickValue);
  565. var ms = Math.floor(msFloat);
  566. var remainder = nanoRemainder(msFloat);
  567. var nanosTotal = nanos + remainder;
  568. var tickTo = clock.now + ms;
  569. if (msFloat < 0) {
  570. throw new TypeError("Negative ticks are not supported");
  571. }
  572. // adjust for positive overflow
  573. if (nanosTotal >= 1e6) {
  574. tickTo += 1;
  575. nanosTotal -= 1e6;
  576. }
  577. nanos = nanosTotal;
  578. var tickFrom = clock.now;
  579. var previous = clock.now;
  580. var timer, firstException, oldNow;
  581. clock.duringTick = true;
  582. // perform microtasks
  583. oldNow = clock.now;
  584. runJobs(clock);
  585. if (oldNow !== clock.now) {
  586. // compensate for any setSystemTime() call during microtask callback
  587. tickFrom += clock.now - oldNow;
  588. tickTo += clock.now - oldNow;
  589. }
  590. // perform each timer in the requested range
  591. timer = firstTimerInRange(clock, tickFrom, tickTo);
  592. while (timer && tickFrom <= tickTo) {
  593. if (clock.timers[timer.id]) {
  594. tickFrom = timer.callAt;
  595. clock.now = timer.callAt;
  596. oldNow = clock.now;
  597. try {
  598. runJobs(clock);
  599. callTimer(clock, timer);
  600. } catch (e) {
  601. firstException = firstException || e;
  602. }
  603. // compensate for any setSystemTime() call during timer callback
  604. if (oldNow !== clock.now) {
  605. tickFrom += clock.now - oldNow;
  606. tickTo += clock.now - oldNow;
  607. previous += clock.now - oldNow;
  608. }
  609. }
  610. timer = firstTimerInRange(clock, previous, tickTo);
  611. previous = tickFrom;
  612. }
  613. // perform process.nextTick()s again
  614. oldNow = clock.now;
  615. runJobs(clock);
  616. if (oldNow !== clock.now) {
  617. // compensate for any setSystemTime() call during process.nextTick() callback
  618. tickFrom += clock.now - oldNow;
  619. tickTo += clock.now - oldNow;
  620. }
  621. clock.duringTick = false;
  622. // corner case: during runJobs, new timers were scheduled which could be in the range [clock.now, tickTo]
  623. timer = firstTimerInRange(clock, tickFrom, tickTo);
  624. if (timer) {
  625. try {
  626. clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range
  627. } catch (e) {
  628. firstException = firstException || e;
  629. }
  630. } else {
  631. // no timers remaining in the requested range: move the clock all the way to the end
  632. clock.now = tickTo;
  633. // update nanos
  634. nanos = nanosTotal;
  635. }
  636. if (firstException) {
  637. throw firstException;
  638. }
  639. return clock.now;
  640. };
  641. clock.next = function next() {
  642. runJobs(clock);
  643. var timer = firstTimer(clock);
  644. if (!timer) {
  645. return clock.now;
  646. }
  647. clock.duringTick = true;
  648. try {
  649. clock.now = timer.callAt;
  650. callTimer(clock, timer);
  651. runJobs(clock);
  652. return clock.now;
  653. } finally {
  654. clock.duringTick = false;
  655. }
  656. };
  657. clock.runAll = function runAll() {
  658. var numTimers, i;
  659. runJobs(clock);
  660. for (i = 0; i < clock.loopLimit; i++) {
  661. if (!clock.timers) {
  662. return clock.now;
  663. }
  664. numTimers = keys(clock.timers).length;
  665. if (numTimers === 0) {
  666. return clock.now;
  667. }
  668. clock.next();
  669. }
  670. throw new Error("Aborting after running " + clock.loopLimit + " timers, assuming an infinite loop!");
  671. };
  672. clock.runToFrame = function runToFrame() {
  673. return clock.tick(getTimeToNextFrame());
  674. };
  675. clock.runToLast = function runToLast() {
  676. var timer = lastTimer(clock);
  677. if (!timer) {
  678. runJobs(clock);
  679. return clock.now;
  680. }
  681. return clock.tick(timer.callAt - clock.now);
  682. };
  683. clock.reset = function reset() {
  684. nanos = 0;
  685. clock.timers = {};
  686. clock.jobs = [];
  687. clock.now = start;
  688. };
  689. clock.setSystemTime = function setSystemTime(systemTime) {
  690. // determine time difference
  691. var newNow = getEpoch(systemTime);
  692. var difference = newNow - clock.now;
  693. var id, timer;
  694. adjustedSystemTime[0] = difference;
  695. adjustedSystemTime[1] = nanos;
  696. // update 'system clock'
  697. clock.now = newNow;
  698. nanos = 0;
  699. // update timers and intervals to keep them stable
  700. for (id in clock.timers) {
  701. if (clock.timers.hasOwnProperty(id)) {
  702. timer = clock.timers[id];
  703. timer.createdAt += difference;
  704. timer.callAt += difference;
  705. }
  706. }
  707. };
  708. if (performancePresent) {
  709. clock.performance = Object.create(null);
  710. if (hasPerformancePrototype) {
  711. var proto = _global.Performance.prototype;
  712. Object
  713. .getOwnPropertyNames(proto)
  714. .forEach(function (name) {
  715. clock.performance[name] = NOOP;
  716. });
  717. }
  718. clock.performance.now = function lolexNow() {
  719. var hrt = hrtime();
  720. var millis = (hrt[0] * 1000 + hrt[1] / 1e6);
  721. return millis;
  722. };
  723. }
  724. if (hrtimePresent) {
  725. clock.hrtime = hrtime;
  726. }
  727. return clock;
  728. }
  729. /**
  730. * @param config {Object} optional config
  731. * @param config.target {Object} the target to install timers in (default `window`)
  732. * @param config.now {number|Date} a number (in milliseconds) or a Date object (default epoch)
  733. * @param config.toFake {string[]} names of the methods that should be faked.
  734. * @param config.loopLimit {number} the maximum number of timers that will be run when calling runAll()
  735. * @param config.shouldAdvanceTime {Boolean} tells lolex to increment mocked time automatically (default false)
  736. * @param config.advanceTimeDelta {Number} increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
  737. */
  738. function install(config) {
  739. if ( arguments.length > 1 || config instanceof Date || Array.isArray(config) || typeof config === "number") {
  740. throw new TypeError("lolex.install called with " + String(config) +
  741. " lolex 2.0+ requires an object parameter - see https://github.com/sinonjs/lolex");
  742. }
  743. config = typeof config !== "undefined" ? config : {};
  744. config.shouldAdvanceTime = config.shouldAdvanceTime || false;
  745. config.advanceTimeDelta = config.advanceTimeDelta || 20;
  746. var i, l;
  747. var target = config.target || _global;
  748. var clock = createClock(config.now, config.loopLimit);
  749. clock.uninstall = function () {
  750. return uninstall(clock, target, config);
  751. };
  752. clock.methods = config.toFake || [];
  753. if (clock.methods.length === 0) {
  754. // do not fake nextTick by default - GitHub#126
  755. clock.methods = keys(timers).filter(function (key) {return key !== "nextTick";});
  756. }
  757. for (i = 0, l = clock.methods.length; i < l; i++) {
  758. if (clock.methods[i] === "hrtime") {
  759. if (target.process && typeof target.process.hrtime === "function") {
  760. hijackMethod(target.process, clock.methods[i], clock);
  761. }
  762. } else if (clock.methods[i] === "nextTick") {
  763. if (target.process && typeof target.process.nextTick === "function") {
  764. hijackMethod(target.process, clock.methods[i], clock);
  765. }
  766. } else {
  767. if (clock.methods[i] === "setInterval" && config.shouldAdvanceTime === true) {
  768. var intervalTick = doIntervalTick.bind(null, clock, config.advanceTimeDelta);
  769. var intervalId = target[clock.methods[i]](
  770. intervalTick,
  771. config.advanceTimeDelta);
  772. clock.attachedInterval = intervalId;
  773. }
  774. hijackMethod(target, clock.methods[i], clock);
  775. }
  776. }
  777. return clock;
  778. }
  779. return {
  780. timers: timers,
  781. createClock: createClock,
  782. install: install,
  783. withGlobal: withGlobal
  784. };
  785. }
  786. var defaultImplementation = withGlobal(global || window);
  787. exports.timers = defaultImplementation.timers;
  788. exports.createClock = defaultImplementation.createClock;
  789. exports.install = defaultImplementation.install;
  790. exports.withGlobal = withGlobal;
  791. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  792. },{}]},{},[1])(1)
  793. });