added unit testing, and started implementing unit tests...phew

This commit is contained in:
Josh Burman
2019-03-12 22:28:02 -04:00
parent 74aad4a957
commit e8c2539f1b
3489 changed files with 464813 additions and 88 deletions

284
node_modules/lolex/History.md generated vendored Normal file
View File

@ -0,0 +1,284 @@
3.1.0 / 2019-02-11
==================
* default timeout set to 50ms
* first implementation of requestIdleCallback and cancelIdleCallback
* fixed accidentally performance.now() -> x.now() replacement
* added queueMicrotask
3.0.0 / 2018-10-08
==================
* Add countTimers method
* Disallow negative ticks (breaking API change!)
* Avoid exposing hrNow
* Fix #207 - round-off errors in `hrtime`
* Truncate sub-nanosecond values for `hrtime`
* Truncate sub-millisceond values for `Date.now()`
v2.7.5 / 2018-09-19
==================
* fix: handle floating point in hrtime (#210)
* fix: reset high resolution timer on clock.reset (#209)
* Add an error when creating a clock with no Date object (#205)
v2.7.4 / 2018-09-05
==================
* performance.mark related fixes for failing Safari, IE 10 and IE 11 tests
v2.7.3 / 2018-09-05
==================
* Fix for #200: TypeError on performance.mark
v2.7.2 / 2018-09-04
==================
* fix(setInterval): parse `timeout` arg to integer (#202)
* Upgrade insecure dependencies with npm audit fix
v2.7.1 / 2018-07-06
==================
* Fix performance replacement on iOS 9.3
v2.7.0 / 2018-05-25
==================
* reset clock to start
* check Performance exists before touching it
v2.6.0 / 2018-05-16
==================
* Fix `reset` and document it publicly Clear microtick jobs and set now to 0 in reset (#179)
* Access Date on `_global` (#178)
v2.5.0 / 2018-05-13
==================
* feat: respect loopLimit in runMicrotasks (#172)
* assign performance as a property, not as a function
v2.4.2 / 2018-05-11
===================
* Upgrade Mochify to v5.6 (#162) fixed #170
* Access `Performance` via `_global` (#168)
v2.4.1 / 2018-05-08
==================
* fix: handle negative infinity timeout (#165)
v2.4.0 / 2018-05-08
==================
* Add `withGlobal` export
* expose runMicrotasks
* Fix that performance.mark is undefined after timer install
v2.3.2 / 2018-01-29
==================
* Add files section to package.json to avoid unnecessary package bloat #154
* Add missing functions in default `toFake` #150
v2.3.1 / 2017-11-22
==================
* bugfix for a setTimeout() or setSystemTime() within a nextTick() call. (#145)
v2.3.0 / 2017-11-08
==================
* Stops leak of (request|cancel)AnimationFrame into global scope. (#143)
* return timers on uninstall
v2.2.0 / 2017-11-07
==================
* Add support for requestAnimationFrame
* fix negative timeout bug
v2.1.3 / 2017-10-03
==================
* add module entry point (#133)
v2.1.2 / 2017-07-25
==================
* - does not fake process.nextTick by default - added .idea folder to .gitignore - fixed documentation - added clock teardowns in tests
* overflowing the timer correctly (issue #67)
v2.1.1 / 2017-07-19
==================
* support passing parameters in nextTick (fixes #122)
v2.1.0 / 2017-07-18
==================
* Throw error on incorrect install use (#112)
* Add support for process.nextTick
* lolex can now attach itself to the system timers and automatically ad… (#102)
* update hrtime when an interval ticks
v2.0.0 / 2017-07-13
==================
* New install() signature
* Add support for performance.now (#106)
* Fix issue with tick(): setSystemClock then throw
* Update old dependencies
* Added support to automatically increment time (#85)
* Changed internal uninstall method signature
v1.6.0 / 2017-02-25
===================
* Use common Sinon.JS eslint config
* Allow install to be called with date object
* Remove wrapper function
* Fixed typo in clock.runAll error
v1.5.2 / 2016-11-10
===================
* Upgrade mocha to latest
* Only overwrite globals when running in IE
1.5.1 / 2016-07-26
==================
* Fix setInterval() behavior with string times
* Incorporate test from PR #65
* Fix issue #59: context object required 'process'
* fixed a case where runAll was called and there are no timers (#70)
* Correct the clear{Interval|Timeout|Immediate} error message when calling `set*` for a different type of timer.
* Lots of minor changes to tooling and the build process
v1.5.0 / 2016-05-18
===================
* 1.5.0
* Check for existence of `process` before using it
* Run to last existing timer
* Add runAll method to run timers until empty
* Turn off Sauce Labs tests for pull requests
* Add tests demonstrating that a fake Date could be created with one argument as a String since this string is in a format recognized by the Date.parse() method.
* Run test-cloud on Travis
* Add process.hrtime()
* Add bithound badge to Readme.md
* Make Travis also run tests in node 4.2
* Update jslint, referee, sinon, browserify, mocha, mochify
* Rename src/lolex.js to src/lolex-src.js to avoid bithound ignoring it
* Add .bithoundrc
v1.4.0 / 2015-12-11
===================
* 1.4.0
* Remove BASH syntax in lint script
* correct test descriptions to match the tests
* correct parseTime() error message so it matches behavior
* don't run test-cloud as part of npm test
* doc: full API reference
* doc: update 'Running tests' section
* doc: update 'Faking the native timers' section
* doc: remove requestAnimationFrame
* Implement clock.next()
* Run lint in CI
* Fix jslint errors
v1.3.2 / 2015-09-22
===================
* 1.3.2
* Fix for breaking shimmed setImmediate
v1.3.1 / 2015-08-20
===================
* Remove error whos reason is no longer accurate
v1.3.0 / 2015-08-19
===================
* 1.3.0
* Throw exception on wrong use of clearXYZ()
* Fix for Sinon.JS issue #808 :add setSystemTime() function
* Fix for Sinon.JS issue #766: clearTimeout() no longer clears Immediate/Interval and vice versa
* Update Readme.md to point to LICENSE file
* Fix error in readme about running tests
* Fix for warning about SPDX license format on npm install
v1.2.2 / 2015-07-22
===================
* 1.2.2
* Fixing lint mistake
* Update travis to use node@0.12
* Fix complaint about missing fake setImmediate
* Use license in package.json
v1.2.1 / 2015-01-06
===================
* New build
* Dodge JSLint...
* Up version
* Proper fix for writable globals in IE
* Make timers writable in old IEs
v1.2.0 / 2014-12-12
===================
* 1.2.0
* Fix Sinon.JS issue 624
* Lint the test files also
* Add .jslintrc
* Delay setImmediate if it is during tick call
* Add test case
* Test behaviour of hasOwnProperty beforehand
* Compare now() with delta
* Use undefined for defined predicate
* Put setImmediate in toFake list
* Capture clock instance for uninstall
* Restore commented out tests
* Add JSLint verification to test
* Configure Travis to run tests in node 0.10.x
* Add .editorconfig
* Fail when faking Date but not setTimeout/setInterval
v1.1.10 / 2014-11-14
====================
* 1.1.0 Fixes setImmediate problems
* Rely on `timer` initialization to null
* Timer assembly occurs at addTimer callsites
* Sort immediate timers before non-immediate
* Add createdAt to timers
* Sort timers by multiple criteria, not just callAt
* Refactor firstTimerInRange
* Rename `timeouts` property to `timers`
* addTimer is options-driven
v1.0.0 / 2014-11-12
===================
* Add built file for browsers
* Fix URL
* Don't run tests that require global.__proto__ on IE 9 and IE 10
* Add "bundle" script to create standalone UMD bundle with browserify
* Float with new test framework versions
* Remove redundant module prefix
* Let Browserify set "global" for us
* Change test framework from Buster to Mocha and Mochify
* Make timer functions independent on `this`
* Change APIs according to Readme
* Change clock-creating interface
* Change Github paths
* Basically working extraction from Sinon.JS

11
node_modules/lolex/LICENSE generated vendored Normal file
View File

@ -0,0 +1,11 @@
Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

317
node_modules/lolex/Readme.md generated vendored Normal file
View File

@ -0,0 +1,317 @@
# Lolex [![Build Status](https://travis-ci.org/sinonjs/lolex.svg?branch=master)](https://travis-ci.org/sinonjs/lolex)
JavaScript implementation of the timer APIs; `setTimeout`, `clearTimeout`, `setImmediate`, `clearImmediate`, `setInterval`, `clearInterval`, `requestAnimationFrame`, and `cancelAnimationFrame`, along with a clock instance that controls the flow of time. Lolex also provides a `Date` implementation that gets its time from the clock.
In addition in browser environment lolex provides a `performance` implementation that gets its time from the clock. In Node environments lolex provides a `nextTick` implementation that is synchronized with the clock - and a `process.hrtime` shim that works with the clock.
Lolex can be used to simulate passing time in automated tests and other
situations where you want the scheduling semantics, but don't want to actually
wait (however, from version 2.0 lolex supports those of you who would like to wait too).
Lolex is extracted from [Sinon.JS](https://github.com/sinonjs/sinon.js).
## Installation
Lolex can be used in both Node and browser environments. Installation is as easy as
```sh
npm install lolex
```
If you want to use Lolex in a browser you can use [the pre-built
version](https://github.com/sinonjs/lolex/blob/master/lolex.js) available in the repo
and the npm package. Using npm you only need to reference `./node_modules/lolex/lolex.js` in your `<script>` tags.
You are always free to [build it yourself](https://github.com/sinonjs/lolex/blob/53ea4d9b9e5bcff53cc7c9755dc9aa340368cf1c/package.json#L22), of course.
## Usage
To use lolex, create a new clock, schedule events on it using the timer
functions and pass time using the `tick` method.
```js
// In the browser distribution, a global `lolex` is already available
var lolex = require("lolex");
var clock = lolex.createClock();
clock.setTimeout(function () {
console.log("The poblano is a mild chili pepper originating in the state of Puebla, Mexico.");
}, 15);
// ...
clock.tick(15);
```
Upon executing the last line, an interesting fact about the
[Poblano](http://en.wikipedia.org/wiki/Poblano) will be printed synchronously to
the screen. If you want to simulate asynchronous behavior, you have to use your
imagination when calling the various functions.
The `next`, `runAll`, `runToFrame`, and `runToLast` methods are available to advance the clock. See the
API Reference for more details.
### Faking the native timers
When using lolex to test timers, you will most likely want to replace the native
timers such that calling `setTimeout` actually schedules a callback with your
clock instance, not the browser's internals.
Calling `install` with no arguments achieves this. You can call `uninstall`
later to restore things as they were again.
```js
// In the browser distribution, a global `lolex` is already available
var lolex = require("lolex");
var clock = lolex.install();
// Equivalent to
// var clock = lolex.install(typeof global !== "undefined" ? global : window);
setTimeout(fn, 15); // Schedules with clock.setTimeout
clock.uninstall();
// setTimeout is restored to the native implementation
```
To hijack timers in another context pass it to the `install` method.
```js
var lolex = require("lolex");
var context = {
setTimeout: setTimeout // By default context.setTimeout uses the global setTimeout
}
var clock = lolex.install({target: context});
context.setTimeout(fn, 15); // Schedules with clock.setTimeout
clock.uninstall();
// context.setTimeout is restored to the original implementation
```
Usually you want to install the timers onto the global object, so call `install`
without arguments.
#### Automatically incrementing mocked time
Since version 2.0 Lolex supports the possibility to attach the faked timers
to any change in the real system time. This basically means you no longer need
to `tick()` the clock in a situation where you won't know **when** to call `tick()`.
Please note that this is achieved using the original setImmediate() API at a certain
configurable interval `config.advanceTimeDelta` (default: 20ms). Meaning time would
be incremented every 20ms, not in real time.
An example would be:
```js
var lolex = require("lolex");
var clock = lolex.install({shouldAdvanceTime: true, advanceTimeDelta: 40});
setTimeout(() => {
console.log('this just timed out'); //executed after 40ms
}, 30);
setImmediate(() => {
console.log('not so immediate'); //executed after 40ms
});
setTimeout(() => {
console.log('this timed out after'); //executed after 80ms
clock.uninstall();
}, 50);
```
## API Reference
### `var clock = lolex.createClock([now[, loopLimit]])`
Creates a clock. The default
[epoch](https://en.wikipedia.org/wiki/Epoch_%28reference_date%29) is `0`.
The `now` argument may be a number (in milliseconds) or a Date object.
The `loopLimit` argument sets the maximum number of timers that will be run when calling `runAll()` before assuming that we have an infinite loop and throwing an error. The default is `1000`.
### `var clock = lolex.install([config])`
Installs lolex using the specified config (otherwise with epoch `0` on the global scope). The following configuration options are available
Parameter | Type | Default | Description
--------- | ---- | ------- | ------------
`config.target`| Object | global | installs lolex onto the specified target context
`config.now` | Number/Date | 0 | installs lolex with the specified unix epoch
`config.toFake` | String[] | ["setTimeout", "clearTimeout", "setImmediate", "clearImmediate","setInterval", "clearInterval", "Date", "requestAnimationFrame", "cancelAnimationFrame", "hrtime"] | an array with explicit function names to hijack. *When not set, lolex will automatically fake all methods **except** `nextTick`* e.g., `lolex.install({ toFake: ["setTimeout","nextTick"]})` will fake only `setTimeout` and `nextTick`
`config.loopLimit` | Number | 1000 | the maximum number of timers that will be run when calling runAll()
`config.shouldAdvanceTime` | Boolean | false | tells lolex to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change in the real system time)
`config.advanceTimeDelta` | Number | 20 | relevant only when using with `shouldAdvanceTime: true`. increment mocked time by `advanceTimeDelta` ms every `advanceTimeDelta` ms change in the real system time.
### `var id = clock.setTimeout(callback, timeout)`
Schedules the callback to be fired once `timeout` milliseconds have ticked by.
In Node.js `setTimeout` returns a timer object. Lolex will do the same, however
its `ref()` and `unref()` methods have no effect.
In browsers a timer ID is returned.
### `clock.clearTimeout(id)`
Clears the timer given the ID or timer object, as long as it was created using
`setTimeout`.
### `var id = clock.setInterval(callback, timeout)`
Schedules the callback to be fired every time `timeout` milliseconds have ticked
by.
In Node.js `setInterval` returns a timer object. Lolex will do the same, however
its `ref()` and `unref()` methods have no effect.
In browsers a timer ID is returned.
### `clock.clearInterval(id)`
Clears the timer given the ID or timer object, as long as it was created using
`setInterval`.
### `var id = clock.setImmediate(callback)`
Schedules the callback to be fired once `0` milliseconds have ticked by. Note
that you'll still have to call `clock.tick()` for the callback to fire. If
called during a tick the callback won't fire until `1` millisecond has ticked
by.
In Node.js `setImmediate` returns a timer object. Lolex will do the same,
however its `ref()` and `unref()` methods have no effect.
In browsers a timer ID is returned.
### `clock.clearImmediate(id)`
Clears the timer given the ID or timer object, as long as it was created using
`setImmediate`.
### `clock.requestAnimationFrame(callback)`
Schedules the callback to be fired on the next animation frame, which runs every
16 ticks. Returns an `id` which can be used to cancel the callback. This is
available in both browser & node environments.
### `clock.cancelAnimationFrame(id)`
Cancels the callback scheduled by the provided id.
### `clock.countTimers()`
Returns the number of waiting timers. This can be used to assert that a test
finishes without leaking any timers.
### `clock.hrtime(prevTime?)`
Only available in Node.js, mimicks process.hrtime().
### `clock.nextTick(callback)`
Only available in Node.js, mimics `process.nextTick` to enable completely synchronous testing flows.
### `clock.performance.now()`
Only available in browser environments, mimicks performance.now().
### `clock.tick(time)`
Advance the clock, firing callbacks if necessary. `time` may be the number of
milliseconds to advance the clock by or a human-readable string. Valid string
formats are `"08"` for eight seconds, `"01:00"` for one minute and `"02:34:10"`
for two hours, 34 minutes and ten seconds.
### `clock.next()`
Advances the clock to the the moment of the first scheduled timer, firing it.
### `clock.reset()`
Removes all timers and ticks without firing them, and sets `now` to `config.now`
that was provided to `lolex.install` or to `0` if `config.now` was not provided.
Useful to reset the state of the clock without having to `uninstall` and `install` it.
### `clock.runAll()`
This runs all pending timers until there are none remaining. If new timers are added while it is executing they will be run as well.
This makes it easier to run asynchronous tests to completion without worrying about the number of timers they use, or the delays in those timers.
It runs a maximum of `loopLimit` times after which it assumes there is an infinite loop of timers and throws an error.
### `clock.runMicrotasks()`
This runs all pending microtasks scheduled with `nextTick` but none of the timers and is mostly useful for libraries using lolex underneath and for running `nextTick` items without any timers.
### `clock.runToFrame()`
Advances the clock to the next frame, firing all scheduled animation frame callbacks,
if any, for that frame as well as any other timers scheduled along the way.
### `clock.runToLast()`
This takes note of the last scheduled timer when it is run, and advances the
clock to that time firing callbacks as necessary.
If new timers are added while it is executing they will be run only if they
would occur before this time.
This is useful when you want to run a test to completion, but the test recursively
sets timers that would cause `runAll` to trigger an infinite loop warning.
### `clock.setSystemTime([now])`
This simulates a user changing the system clock while your program is running.
It affects the current time but it does not in itself cause e.g. timers to fire;
they will fire exactly as they would have done without the call to
setSystemTime().
### `clock.uninstall()`
Restores the original methods on the `target` that was passed to
`lolex.install`, or the native timers if no `target` was given.
### `Date`
Implements the `Date` object but using the clock to provide the correct time.
### `Performance`
Implements the `now` method of the [`Performance`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) object but using the clock to provide the correct time. Only available in environments that support the Performance object (browsers mostly).
### `lolex.withGlobal`
In order to support creating clocks based on separate or sandboxed environments (such as JSDOM), Lolex exports a factory method which takes single argument `global`, which it inspects to figure out what to mock and what features to support. When invoking this function with a global, you will get back an object with `timers`, `createClock` and `install` - same as the regular Lolex exports only based on the passed in global instead of the global environment.
## Running tests
Lolex has a comprehensive test suite. If you're thinking of contributing bug
fixes or suggesting new features, you need to make sure you have not broken any
tests. You are also expected to add tests for any new behavior.
### On node:
```sh
npm test
```
Or, if you prefer more verbose output:
```
$(npm bin)/mocha ./test/lolex-test.js
```
### In the browser
[Mochify](https://github.com/mantoni/mochify.js) is used to run the tests in
PhantomJS. Make sure you have `phantomjs` installed. Then:
```sh
npm test-headless
```
## License
BSD 3-clause "New" or "Revised" License (see LICENSE file)

946
node_modules/lolex/lolex.js generated vendored Normal file
View File

@ -0,0 +1,946 @@
(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){
(function (global){
"use strict";
function withGlobal(_global) {
var userAgent = _global.navigator && _global.navigator.userAgent;
var isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1;
var maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
// Make properties writable in IE, as per
// http://www.adequatelygood.com/Replacing-setTimeout-Globally.html
if (isRunningInIE) {
_global.setTimeout = _global.setTimeout;
_global.clearTimeout = _global.clearTimeout;
_global.setInterval = _global.setInterval;
_global.clearInterval = _global.clearInterval;
_global.Date = _global.Date;
}
// setImmediate is not a standard function
// avoid adding the prop to the window object if not present
if (_global.setImmediate !== undefined) {
_global.setImmediate = _global.setImmediate;
_global.clearImmediate = _global.clearImmediate;
}
// node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref()
// browsers, a number.
// see https://github.com/cjohansen/Sinon.JS/pull/436
var NOOP = function () { return undefined; };
var timeoutResult = _global.setTimeout(NOOP, 0);
var addTimerReturnsObject = typeof timeoutResult === "object";
var hrtimePresent = (_global.process && typeof _global.process.hrtime === "function");
var nextTickPresent = (_global.process && typeof _global.process.nextTick === "function");
var performancePresent = (_global.performance && typeof _global.performance.now === "function");
var hasPerformancePrototype = (_global.Performance && (typeof _global.Performance).match(/^(function|object)$/));
var queueMicrotaskPresent = (typeof _global.queueMicrotask === "function");
var requestAnimationFramePresent = (
_global.requestAnimationFrame && typeof _global.requestAnimationFrame === "function"
);
var cancelAnimationFramePresent = (
_global.cancelAnimationFrame && typeof _global.cancelAnimationFrame === "function"
);
var requestIdleCallbackPresent = (
_global.requestIdleCallback && typeof _global.requestIdleCallback === "function"
);
var cancelIdleCallbackPresent = (
_global.cancelIdleCallback && typeof _global.cancelIdleCallback === "function"
);
_global.clearTimeout(timeoutResult);
var NativeDate = _global.Date;
var uniqueTimerId = 1;
function isNumberFinite(num) {
if (Number.isFinite) {
return Number.isFinite(num);
}
if (typeof num !== "number") {
return false;
}
return isFinite(num);
}
/**
* Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
* number of milliseconds. This is used to support human-readable strings passed
* to clock.tick()
*/
function parseTime(str) {
if (!str) {
return 0;
}
var strings = str.split(":");
var l = strings.length;
var i = l;
var ms = 0;
var parsed;
if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
throw new Error("tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits");
}
while (i--) {
parsed = parseInt(strings[i], 10);
if (parsed >= 60) {
throw new Error("Invalid time " + str);
}
ms += parsed * Math.pow(60, (l - i - 1));
}
return ms * 1000;
}
/**
* Get the decimal part of the millisecond value as nanoseconds
*
* @param {Number} msFloat the number of milliseconds
* @returns {Number} an integer number of nanoseconds in the range [0,1e6)
*
* Example: nanoRemainer(123.456789) -> 456789
*/
function nanoRemainder(msFloat) {
var modulo = 1e6;
var remainder = (msFloat * 1e6) % modulo;
var positiveRemainder = remainder < 0 ? remainder + modulo : remainder;
return Math.floor(positiveRemainder);
}
/**
* Used to grok the `now` parameter to createClock.
* @param epoch {Date|number} the system time
*/
function getEpoch(epoch) {
if (!epoch) { return 0; }
if (typeof epoch.getTime === "function") { return epoch.getTime(); }
if (typeof epoch === "number") { return epoch; }
throw new TypeError("now should be milliseconds since UNIX epoch");
}
function inRange(from, to, timer) {
return timer && timer.callAt >= from && timer.callAt <= to;
}
function mirrorDateProperties(target, source) {
var prop;
for (prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
// set special now implementation
if (source.now) {
target.now = function now() {
return target.clock.now;
};
} else {
delete target.now;
}
// set special toSource implementation
if (source.toSource) {
target.toSource = function toSource() {
return source.toSource();
};
} else {
delete target.toSource;
}
// set special toString implementation
target.toString = function toString() {
return source.toString();
};
target.prototype = source.prototype;
target.parse = source.parse;
target.UTC = source.UTC;
target.prototype.toUTCString = source.prototype.toUTCString;
return target;
}
function createDate() {
function ClockDate(year, month, date, hour, minute, second, ms) {
// Defensive and verbose to avoid potential harm in passing
// explicit undefined when user does not pass argument
switch (arguments.length) {
case 0:
return new NativeDate(ClockDate.clock.now);
case 1:
return new NativeDate(year);
case 2:
return new NativeDate(year, month);
case 3:
return new NativeDate(year, month, date);
case 4:
return new NativeDate(year, month, date, hour);
case 5:
return new NativeDate(year, month, date, hour, minute);
case 6:
return new NativeDate(year, month, date, hour, minute, second);
default:
return new NativeDate(year, month, date, hour, minute, second, ms);
}
}
return mirrorDateProperties(ClockDate, NativeDate);
}
function enqueueJob(clock, job) {
// enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
if (!clock.jobs) {
clock.jobs = [];
}
clock.jobs.push(job);
}
function runJobs(clock) {
// runs all microtick-deferred tasks - ecma262/#sec-runjobs
if (!clock.jobs) {
return;
}
for (var i = 0; i < clock.jobs.length; i++) {
var job = clock.jobs[i];
job.func.apply(null, job.args);
if (clock.loopLimit && i > clock.loopLimit) {
throw new Error("Aborting after running " + clock.loopLimit + " timers, assuming an infinite loop!");
}
}
clock.jobs = [];
}
function addTimer(clock, timer) {
if (timer.func === undefined) {
throw new Error("Callback must be provided to timer calls");
}
timer.type = timer.immediate ? "Immediate" : "Timeout";
if (timer.hasOwnProperty("delay")) {
if (!isNumberFinite(timer.delay)) {
timer.delay = 0;
}
timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
timer.delay = Math.max(0, timer.delay);
}
if (timer.hasOwnProperty("interval")) {
timer.type = "Interval";
timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
}
if (timer.hasOwnProperty("animation")) {
timer.type = "AnimationFrame";
timer.animation = true;
}
if (!clock.timers) {
clock.timers = {};
}
timer.id = uniqueTimerId++;
timer.createdAt = clock.now;
timer.callAt = clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
clock.timers[timer.id] = timer;
if (addTimerReturnsObject) {
var res = {
id: timer.id,
ref: function () { return res; },
unref: function () { return res; },
refresh: function () { return res; }
};
return res;
}
return timer.id;
}
/* eslint consistent-return: "off" */
function compareTimers(a, b) {
// Sort first by absolute timing
if (a.callAt < b.callAt) {
return -1;
}
if (a.callAt > b.callAt) {
return 1;
}
// Sort next by immediate, immediate timers take precedence
if (a.immediate && !b.immediate) {
return -1;
}
if (!a.immediate && b.immediate) {
return 1;
}
// Sort next by creation time, earlier-created timers take precedence
if (a.createdAt < b.createdAt) {
return -1;
}
if (a.createdAt > b.createdAt) {
return 1;
}
// Sort next by id, lower-id timers take precedence
if (a.id < b.id) {
return -1;
}
if (a.id > b.id) {
return 1;
}
// As timer ids are unique, no fallback `0` is necessary
}
function firstTimerInRange(clock, from, to) {
var timers = clock.timers;
var timer = null;
var id, isInRange;
for (id in timers) {
if (timers.hasOwnProperty(id)) {
isInRange = inRange(from, to, timers[id]);
if (isInRange && (!timer || compareTimers(timer, timers[id]) === 1)) {
timer = timers[id];
}
}
}
return timer;
}
function firstTimer(clock) {
var timers = clock.timers;
var timer = null;
var id;
for (id in timers) {
if (timers.hasOwnProperty(id)) {
if (!timer || compareTimers(timer, timers[id]) === 1) {
timer = timers[id];
}
}
}
return timer;
}
function lastTimer(clock) {
var timers = clock.timers;
var timer = null;
var id;
for (id in timers) {
if (timers.hasOwnProperty(id)) {
if (!timer || compareTimers(timer, timers[id]) === -1) {
timer = timers[id];
}
}
}
return timer;
}
function callTimer(clock, timer) {
if (typeof timer.interval === "number") {
clock.timers[timer.id].callAt += timer.interval;
} else {
delete clock.timers[timer.id];
}
if (typeof timer.func === "function") {
timer.func.apply(null, timer.args);
} else {
/* eslint no-eval: "off" */
eval(timer.func);
}
}
function clearTimer(clock, timerId, ttype) {
if (!timerId) {
// null appears to be allowed in most browsers, and appears to be
// relied upon by some libraries, like Bootstrap carousel
return;
}
if (!clock.timers) {
clock.timers = {};
}
// in Node, timerId is an object with .ref()/.unref(), and
// its .id field is the actual timer id.
if (typeof timerId === "object") {
timerId = timerId.id;
}
if (clock.timers.hasOwnProperty(timerId)) {
// check that the ID matches a timer of the correct type
var timer = clock.timers[timerId];
if (timer.type === ttype) {
delete clock.timers[timerId];
} else {
var clear = ttype === "AnimationFrame" ? "cancelAnimationFrame" : "clear" + ttype;
var schedule = timer.type === "AnimationFrame" ? "requestAnimationFrame" : "set" + timer.type;
throw new Error("Cannot clear timer: timer created with " + schedule
+ "() but cleared with " + clear + "()");
}
}
}
function uninstall(clock, target, config) {
var method,
i,
l;
var installedHrTime = "_hrtime";
var installedNextTick = "_nextTick";
for (i = 0, l = clock.methods.length; i < l; i++) {
method = clock.methods[i];
if (method === "hrtime" && target.process) {
target.process.hrtime = clock[installedHrTime];
} else if (method === "nextTick" && target.process) {
target.process.nextTick = clock[installedNextTick];
} else if (method === "performance") {
target[method] = clock["_" + method];
} else {
if (target[method] && target[method].hadOwnProperty) {
target[method] = clock["_" + method];
if (method === "clearInterval" && config.shouldAdvanceTime === true) {
target[method](clock.attachedInterval);
}
} else {
try {
delete target[method];
} catch (ignore) { /* eslint empty-block: "off" */ }
}
}
}
// Prevent multiple executions which will completely remove these props
clock.methods = [];
// return pending timers, to enable checking what timers remained on uninstall
if (!clock.timers) {
return [];
}
return Object.keys(clock.timers).map(function mapper(key) {
return clock.timers[key];
});
}
function hijackMethod(target, method, clock) {
var prop;
clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method);
clock["_" + method] = target[method];
if (method === "Date") {
var date = mirrorDateProperties(clock[method], target[method]);
target[method] = date;
} else if (method === "performance") {
target[method] = clock[method];
} else {
target[method] = function () {
return clock[method].apply(clock, arguments);
};
for (prop in clock[method]) {
if (clock[method].hasOwnProperty(prop)) {
target[method][prop] = clock[method][prop];
}
}
}
target[method].clock = clock;
}
function doIntervalTick(clock, advanceTimeDelta) {
clock.tick(advanceTimeDelta);
}
var timers = {
setTimeout: _global.setTimeout,
clearTimeout: _global.clearTimeout,
setImmediate: _global.setImmediate,
clearImmediate: _global.clearImmediate,
setInterval: _global.setInterval,
clearInterval: _global.clearInterval,
Date: _global.Date
};
if (hrtimePresent) {
timers.hrtime = _global.process.hrtime;
}
if (nextTickPresent) {
timers.nextTick = _global.process.nextTick;
}
if (performancePresent) {
timers.performance = _global.performance;
}
if (requestAnimationFramePresent) {
timers.requestAnimationFrame = _global.requestAnimationFrame;
}
if (queueMicrotaskPresent) {
timers.queueMicrotask = _global.queueMicrotask;
}
if (cancelAnimationFramePresent) {
timers.cancelAnimationFrame = _global.cancelAnimationFrame;
}
if (requestIdleCallbackPresent) {
timers.requestIdleCallback = _global.requestIdleCallback;
}
if (cancelIdleCallbackPresent) {
timers.cancelIdleCallback = _global.cancelIdleCallback;
}
var keys = Object.keys || function (obj) {
var ks = [];
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
ks.push(key);
}
}
return ks;
};
/**
* @param start {Date|number} the system time - non-integer values are floored
* @param loopLimit {number} maximum number of timers that will be run when calling runAll()
*/
function createClock(start, loopLimit) {
start = Math.floor(getEpoch(start));
loopLimit = loopLimit || 1000;
var nanos = 0;
var adjustedSystemTime = [0, 0]; // [millis, nanoremainder]
if (NativeDate === undefined) {
throw new Error("The global scope doesn't have a `Date` object"
+ " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)");
}
var clock = {
now: start,
timeouts: {},
Date: createDate(),
loopLimit: loopLimit
};
clock.Date.clock = clock;
function getTimeToNextFrame() {
return 16 - ((clock.now - start) % 16);
}
function hrtime(prev) {
var millisSinceStart = clock.now - adjustedSystemTime[0] - start;
var secsSinceStart = Math.floor( millisSinceStart / 1000);
var remainderInNanos = (millisSinceStart - secsSinceStart * 1e3 ) * 1e6 + nanos - adjustedSystemTime[1];
if (Array.isArray(prev)) {
if ( prev[1] > 1e9 ) {
throw new TypeError("Number of nanoseconds can't exceed a billion");
}
var oldSecs = prev[0];
var nanoDiff = remainderInNanos - prev[1];
var secDiff = secsSinceStart - oldSecs;
if (nanoDiff < 0) {
nanoDiff += 1e9;
secDiff -= 1;
}
return [secDiff, nanoDiff];
}
return [secsSinceStart, remainderInNanos];
}
clock.requestIdleCallback = function requestIdleCallback(func, timeout) {
var timeToNextIdlePeriod = 0;
if (clock.countTimers() > 0) {
timeToNextIdlePeriod = 50; // const for now
}
var result = addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 2),
delay: typeof timeout === "undefined" ? timeToNextIdlePeriod : Math.min(timeout, timeToNextIdlePeriod)
});
return result.id || result;
};
clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
return clearTimer(clock, timerId, "Timeout");
};
clock.setTimeout = function setTimeout(func, timeout) {
return addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 2),
delay: timeout
});
};
clock.clearTimeout = function clearTimeout(timerId) {
return clearTimer(clock, timerId, "Timeout");
};
clock.nextTick = function nextTick(func) {
return enqueueJob(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 1)
});
};
clock.queueMicrotask = function queueMicrotask(func) {
return clock.nextTick(func); // explicitly drop additional arguments
};
clock.setInterval = function setInterval(func, timeout) {
timeout = parseInt(timeout, 10);
return addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 2),
delay: timeout,
interval: timeout
});
};
clock.clearInterval = function clearInterval(timerId) {
return clearTimer(clock, timerId, "Interval");
};
clock.setImmediate = function setImmediate(func) {
return addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 1),
immediate: true
});
};
clock.clearImmediate = function clearImmediate(timerId) {
return clearTimer(clock, timerId, "Immediate");
};
clock.countTimers = function countTimers() {
return Object.keys(clock.timers || {}).length;
};
clock.requestAnimationFrame = function requestAnimationFrame(func) {
var result = addTimer(clock, {
func: func,
delay: getTimeToNextFrame(),
args: [clock.now + getTimeToNextFrame()],
animation: true
});
return result.id || result;
};
clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
return clearTimer(clock, timerId, "AnimationFrame");
};
clock.runMicrotasks = function runMicrotasks() {
runJobs(clock);
};
/**
* @param {tickValue} {String|Number} number of milliseconds or a human-readable value like "01:11:15"
*/
clock.tick = function tick(tickValue) {
var msFloat = typeof tickValue === "number" ? tickValue : parseTime(tickValue);
var ms = Math.floor(msFloat);
var remainder = nanoRemainder(msFloat);
var nanosTotal = nanos + remainder;
var tickTo = clock.now + ms;
if (msFloat < 0) {
throw new TypeError("Negative ticks are not supported");
}
// adjust for positive overflow
if (nanosTotal >= 1e6) {
tickTo += 1;
nanosTotal -= 1e6;
}
nanos = nanosTotal;
var tickFrom = clock.now;
var previous = clock.now;
var timer, firstException, oldNow;
clock.duringTick = true;
// perform microtasks
oldNow = clock.now;
runJobs(clock);
if (oldNow !== clock.now) {
// compensate for any setSystemTime() call during microtask callback
tickFrom += clock.now - oldNow;
tickTo += clock.now - oldNow;
}
// perform each timer in the requested range
timer = firstTimerInRange(clock, tickFrom, tickTo);
while (timer && tickFrom <= tickTo) {
if (clock.timers[timer.id]) {
tickFrom = timer.callAt;
clock.now = timer.callAt;
oldNow = clock.now;
try {
runJobs(clock);
callTimer(clock, timer);
} catch (e) {
firstException = firstException || e;
}
// compensate for any setSystemTime() call during timer callback
if (oldNow !== clock.now) {
tickFrom += clock.now - oldNow;
tickTo += clock.now - oldNow;
previous += clock.now - oldNow;
}
}
timer = firstTimerInRange(clock, previous, tickTo);
previous = tickFrom;
}
// perform process.nextTick()s again
oldNow = clock.now;
runJobs(clock);
if (oldNow !== clock.now) {
// compensate for any setSystemTime() call during process.nextTick() callback
tickFrom += clock.now - oldNow;
tickTo += clock.now - oldNow;
}
clock.duringTick = false;
// corner case: during runJobs, new timers were scheduled which could be in the range [clock.now, tickTo]
timer = firstTimerInRange(clock, tickFrom, tickTo);
if (timer) {
try {
clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range
} catch (e) {
firstException = firstException || e;
}
} else {
// no timers remaining in the requested range: move the clock all the way to the end
clock.now = tickTo;
// update nanos
nanos = nanosTotal;
}
if (firstException) {
throw firstException;
}
return clock.now;
};
clock.next = function next() {
runJobs(clock);
var timer = firstTimer(clock);
if (!timer) {
return clock.now;
}
clock.duringTick = true;
try {
clock.now = timer.callAt;
callTimer(clock, timer);
runJobs(clock);
return clock.now;
} finally {
clock.duringTick = false;
}
};
clock.runAll = function runAll() {
var numTimers, i;
runJobs(clock);
for (i = 0; i < clock.loopLimit; i++) {
if (!clock.timers) {
return clock.now;
}
numTimers = keys(clock.timers).length;
if (numTimers === 0) {
return clock.now;
}
clock.next();
}
throw new Error("Aborting after running " + clock.loopLimit + " timers, assuming an infinite loop!");
};
clock.runToFrame = function runToFrame() {
return clock.tick(getTimeToNextFrame());
};
clock.runToLast = function runToLast() {
var timer = lastTimer(clock);
if (!timer) {
runJobs(clock);
return clock.now;
}
return clock.tick(timer.callAt - clock.now);
};
clock.reset = function reset() {
nanos = 0;
clock.timers = {};
clock.jobs = [];
clock.now = start;
};
clock.setSystemTime = function setSystemTime(systemTime) {
// determine time difference
var newNow = getEpoch(systemTime);
var difference = newNow - clock.now;
var id, timer;
adjustedSystemTime[0] = difference;
adjustedSystemTime[1] = nanos;
// update 'system clock'
clock.now = newNow;
nanos = 0;
// update timers and intervals to keep them stable
for (id in clock.timers) {
if (clock.timers.hasOwnProperty(id)) {
timer = clock.timers[id];
timer.createdAt += difference;
timer.callAt += difference;
}
}
};
if (performancePresent) {
clock.performance = Object.create(null);
if (hasPerformancePrototype) {
var proto = _global.Performance.prototype;
Object
.getOwnPropertyNames(proto)
.forEach(function (name) {
clock.performance[name] = NOOP;
});
}
clock.performance.now = function lolexNow() {
var hrt = hrtime();
var millis = (hrt[0] * 1000 + hrt[1] / 1e6);
return millis;
};
}
if (hrtimePresent) {
clock.hrtime = hrtime;
}
return clock;
}
/**
* @param config {Object} optional config
* @param config.target {Object} the target to install timers in (default `window`)
* @param config.now {number|Date} a number (in milliseconds) or a Date object (default epoch)
* @param config.toFake {string[]} names of the methods that should be faked.
* @param config.loopLimit {number} the maximum number of timers that will be run when calling runAll()
* @param config.shouldAdvanceTime {Boolean} tells lolex to increment mocked time automatically (default false)
* @param config.advanceTimeDelta {Number} increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
*/
function install(config) {
if ( arguments.length > 1 || config instanceof Date || Array.isArray(config) || typeof config === "number") {
throw new TypeError("lolex.install called with " + String(config) +
" lolex 2.0+ requires an object parameter - see https://github.com/sinonjs/lolex");
}
config = typeof config !== "undefined" ? config : {};
config.shouldAdvanceTime = config.shouldAdvanceTime || false;
config.advanceTimeDelta = config.advanceTimeDelta || 20;
var i, l;
var target = config.target || _global;
var clock = createClock(config.now, config.loopLimit);
clock.uninstall = function () {
return uninstall(clock, target, config);
};
clock.methods = config.toFake || [];
if (clock.methods.length === 0) {
// do not fake nextTick by default - GitHub#126
clock.methods = keys(timers).filter(function (key) {return key !== "nextTick";});
}
for (i = 0, l = clock.methods.length; i < l; i++) {
if (clock.methods[i] === "hrtime") {
if (target.process && typeof target.process.hrtime === "function") {
hijackMethod(target.process, clock.methods[i], clock);
}
} else if (clock.methods[i] === "nextTick") {
if (target.process && typeof target.process.nextTick === "function") {
hijackMethod(target.process, clock.methods[i], clock);
}
} else {
if (clock.methods[i] === "setInterval" && config.shouldAdvanceTime === true) {
var intervalTick = doIntervalTick.bind(null, clock, config.advanceTimeDelta);
var intervalId = target[clock.methods[i]](
intervalTick,
config.advanceTimeDelta);
clock.attachedInterval = intervalId;
}
hijackMethod(target, clock.methods[i], clock);
}
}
return clock;
}
return {
timers: timers,
createClock: createClock,
install: install,
withGlobal: withGlobal
};
}
var defaultImplementation = withGlobal(global || window);
exports.timers = defaultImplementation.timers;
exports.createClock = defaultImplementation.createClock;
exports.install = defaultImplementation.install;
exports.withGlobal = withGlobal;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
});

99
node_modules/lolex/package.json generated vendored Normal file
View File

@ -0,0 +1,99 @@
{
"_from": "lolex@^3.1.0",
"_id": "lolex@3.1.0",
"_inBundle": false,
"_integrity": "sha512-zFo5MgCJ0rZ7gQg69S4pqBsLURbFw11X68C18OcJjJQbqaXm2NoTrGl1IMM3TIz0/BnN1tIs2tzmmqvCsOMMjw==",
"_location": "/lolex",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "lolex@^3.1.0",
"name": "lolex",
"escapedName": "lolex",
"rawSpec": "^3.1.0",
"saveSpec": null,
"fetchSpec": "^3.1.0"
},
"_requiredBy": [
"/sinon"
],
"_resolved": "https://registry.npmjs.org/lolex/-/lolex-3.1.0.tgz",
"_shasum": "1a7feb2fefd75b3e3a7f79f0e110d9476e294434",
"_spec": "lolex@^3.1.0",
"_where": "/Users/josh.burman/Projects/braid/node_modules/sinon",
"author": {
"name": "Christian Johansen"
},
"bugs": {
"url": "http://github.com/sinonjs/lolex/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Fake JavaScript timers",
"devDependencies": {
"@sinonjs/referee-sinon": "4.1.0",
"browserify": "16.2.0",
"eslint": "4.19.1",
"eslint-config-sinon": "1.0.3",
"eslint-plugin-ie11": "1.0.0",
"eslint-plugin-mocha": "4.11.0",
"husky": "0.14.3",
"jsdom": "11.10.0",
"lint-staged": "7.0.4",
"mocha": "5.1.0",
"mochify": "5.8.0",
"npm-run-all": "4.1.2"
},
"eslintConfig": {
"extends": "eslint-config-sinon",
"plugins": [
"ie11"
],
"rules": {
"ie11/no-collection-args": [
"error"
],
"ie11/no-for-in-const": [
"error"
],
"ie11/no-loop-func": [
"warn"
],
"ie11/no-weak-collections": [
"error"
]
}
},
"files": [
"src/",
"lolex.js"
],
"homepage": "http://github.com/sinonjs/lolex",
"license": "BSD-3-Clause",
"lint-staged": {
"*.js": "eslint"
},
"main": "./src/lolex-src.js",
"module": "./lolex.js",
"name": "lolex",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/sinonjs/lolex.git"
},
"scripts": {
"bundle": "browserify -s lolex -o lolex.js src/lolex-src.js",
"lint": "eslint .",
"postversion": "./scripts/postversion.sh",
"precommit": "run-p lint test-node",
"prepublishOnly": "npm run bundle",
"preversion": "./scripts/preversion.sh",
"test": "npm run lint && npm run test-node && npm run test-headless",
"test-cloud": "mochify --wd",
"test-headless": "mochify",
"test-node": "mocha test/ integration-test/ -R dot --check-leaks",
"version": "./scripts/version.sh"
},
"version": "3.1.0"
}

940
node_modules/lolex/src/lolex-src.js generated vendored Normal file
View File

@ -0,0 +1,940 @@
"use strict";
function withGlobal(_global) {
var userAgent = _global.navigator && _global.navigator.userAgent;
var isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1;
var maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
// Make properties writable in IE, as per
// http://www.adequatelygood.com/Replacing-setTimeout-Globally.html
if (isRunningInIE) {
_global.setTimeout = _global.setTimeout;
_global.clearTimeout = _global.clearTimeout;
_global.setInterval = _global.setInterval;
_global.clearInterval = _global.clearInterval;
_global.Date = _global.Date;
}
// setImmediate is not a standard function
// avoid adding the prop to the window object if not present
if (_global.setImmediate !== undefined) {
_global.setImmediate = _global.setImmediate;
_global.clearImmediate = _global.clearImmediate;
}
// node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref()
// browsers, a number.
// see https://github.com/cjohansen/Sinon.JS/pull/436
var NOOP = function () { return undefined; };
var timeoutResult = _global.setTimeout(NOOP, 0);
var addTimerReturnsObject = typeof timeoutResult === "object";
var hrtimePresent = (_global.process && typeof _global.process.hrtime === "function");
var nextTickPresent = (_global.process && typeof _global.process.nextTick === "function");
var performancePresent = (_global.performance && typeof _global.performance.now === "function");
var hasPerformancePrototype = (_global.Performance && (typeof _global.Performance).match(/^(function|object)$/));
var queueMicrotaskPresent = (typeof _global.queueMicrotask === "function");
var requestAnimationFramePresent = (
_global.requestAnimationFrame && typeof _global.requestAnimationFrame === "function"
);
var cancelAnimationFramePresent = (
_global.cancelAnimationFrame && typeof _global.cancelAnimationFrame === "function"
);
var requestIdleCallbackPresent = (
_global.requestIdleCallback && typeof _global.requestIdleCallback === "function"
);
var cancelIdleCallbackPresent = (
_global.cancelIdleCallback && typeof _global.cancelIdleCallback === "function"
);
_global.clearTimeout(timeoutResult);
var NativeDate = _global.Date;
var uniqueTimerId = 1;
function isNumberFinite(num) {
if (Number.isFinite) {
return Number.isFinite(num);
}
if (typeof num !== "number") {
return false;
}
return isFinite(num);
}
/**
* Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
* number of milliseconds. This is used to support human-readable strings passed
* to clock.tick()
*/
function parseTime(str) {
if (!str) {
return 0;
}
var strings = str.split(":");
var l = strings.length;
var i = l;
var ms = 0;
var parsed;
if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
throw new Error("tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits");
}
while (i--) {
parsed = parseInt(strings[i], 10);
if (parsed >= 60) {
throw new Error("Invalid time " + str);
}
ms += parsed * Math.pow(60, (l - i - 1));
}
return ms * 1000;
}
/**
* Get the decimal part of the millisecond value as nanoseconds
*
* @param {Number} msFloat the number of milliseconds
* @returns {Number} an integer number of nanoseconds in the range [0,1e6)
*
* Example: nanoRemainer(123.456789) -> 456789
*/
function nanoRemainder(msFloat) {
var modulo = 1e6;
var remainder = (msFloat * 1e6) % modulo;
var positiveRemainder = remainder < 0 ? remainder + modulo : remainder;
return Math.floor(positiveRemainder);
}
/**
* Used to grok the `now` parameter to createClock.
* @param epoch {Date|number} the system time
*/
function getEpoch(epoch) {
if (!epoch) { return 0; }
if (typeof epoch.getTime === "function") { return epoch.getTime(); }
if (typeof epoch === "number") { return epoch; }
throw new TypeError("now should be milliseconds since UNIX epoch");
}
function inRange(from, to, timer) {
return timer && timer.callAt >= from && timer.callAt <= to;
}
function mirrorDateProperties(target, source) {
var prop;
for (prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
// set special now implementation
if (source.now) {
target.now = function now() {
return target.clock.now;
};
} else {
delete target.now;
}
// set special toSource implementation
if (source.toSource) {
target.toSource = function toSource() {
return source.toSource();
};
} else {
delete target.toSource;
}
// set special toString implementation
target.toString = function toString() {
return source.toString();
};
target.prototype = source.prototype;
target.parse = source.parse;
target.UTC = source.UTC;
target.prototype.toUTCString = source.prototype.toUTCString;
return target;
}
function createDate() {
function ClockDate(year, month, date, hour, minute, second, ms) {
// Defensive and verbose to avoid potential harm in passing
// explicit undefined when user does not pass argument
switch (arguments.length) {
case 0:
return new NativeDate(ClockDate.clock.now);
case 1:
return new NativeDate(year);
case 2:
return new NativeDate(year, month);
case 3:
return new NativeDate(year, month, date);
case 4:
return new NativeDate(year, month, date, hour);
case 5:
return new NativeDate(year, month, date, hour, minute);
case 6:
return new NativeDate(year, month, date, hour, minute, second);
default:
return new NativeDate(year, month, date, hour, minute, second, ms);
}
}
return mirrorDateProperties(ClockDate, NativeDate);
}
function enqueueJob(clock, job) {
// enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
if (!clock.jobs) {
clock.jobs = [];
}
clock.jobs.push(job);
}
function runJobs(clock) {
// runs all microtick-deferred tasks - ecma262/#sec-runjobs
if (!clock.jobs) {
return;
}
for (var i = 0; i < clock.jobs.length; i++) {
var job = clock.jobs[i];
job.func.apply(null, job.args);
if (clock.loopLimit && i > clock.loopLimit) {
throw new Error("Aborting after running " + clock.loopLimit + " timers, assuming an infinite loop!");
}
}
clock.jobs = [];
}
function addTimer(clock, timer) {
if (timer.func === undefined) {
throw new Error("Callback must be provided to timer calls");
}
timer.type = timer.immediate ? "Immediate" : "Timeout";
if (timer.hasOwnProperty("delay")) {
if (!isNumberFinite(timer.delay)) {
timer.delay = 0;
}
timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
timer.delay = Math.max(0, timer.delay);
}
if (timer.hasOwnProperty("interval")) {
timer.type = "Interval";
timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
}
if (timer.hasOwnProperty("animation")) {
timer.type = "AnimationFrame";
timer.animation = true;
}
if (!clock.timers) {
clock.timers = {};
}
timer.id = uniqueTimerId++;
timer.createdAt = clock.now;
timer.callAt = clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
clock.timers[timer.id] = timer;
if (addTimerReturnsObject) {
var res = {
id: timer.id,
ref: function () { return res; },
unref: function () { return res; },
refresh: function () { return res; }
};
return res;
}
return timer.id;
}
/* eslint consistent-return: "off" */
function compareTimers(a, b) {
// Sort first by absolute timing
if (a.callAt < b.callAt) {
return -1;
}
if (a.callAt > b.callAt) {
return 1;
}
// Sort next by immediate, immediate timers take precedence
if (a.immediate && !b.immediate) {
return -1;
}
if (!a.immediate && b.immediate) {
return 1;
}
// Sort next by creation time, earlier-created timers take precedence
if (a.createdAt < b.createdAt) {
return -1;
}
if (a.createdAt > b.createdAt) {
return 1;
}
// Sort next by id, lower-id timers take precedence
if (a.id < b.id) {
return -1;
}
if (a.id > b.id) {
return 1;
}
// As timer ids are unique, no fallback `0` is necessary
}
function firstTimerInRange(clock, from, to) {
var timers = clock.timers;
var timer = null;
var id, isInRange;
for (id in timers) {
if (timers.hasOwnProperty(id)) {
isInRange = inRange(from, to, timers[id]);
if (isInRange && (!timer || compareTimers(timer, timers[id]) === 1)) {
timer = timers[id];
}
}
}
return timer;
}
function firstTimer(clock) {
var timers = clock.timers;
var timer = null;
var id;
for (id in timers) {
if (timers.hasOwnProperty(id)) {
if (!timer || compareTimers(timer, timers[id]) === 1) {
timer = timers[id];
}
}
}
return timer;
}
function lastTimer(clock) {
var timers = clock.timers;
var timer = null;
var id;
for (id in timers) {
if (timers.hasOwnProperty(id)) {
if (!timer || compareTimers(timer, timers[id]) === -1) {
timer = timers[id];
}
}
}
return timer;
}
function callTimer(clock, timer) {
if (typeof timer.interval === "number") {
clock.timers[timer.id].callAt += timer.interval;
} else {
delete clock.timers[timer.id];
}
if (typeof timer.func === "function") {
timer.func.apply(null, timer.args);
} else {
/* eslint no-eval: "off" */
eval(timer.func);
}
}
function clearTimer(clock, timerId, ttype) {
if (!timerId) {
// null appears to be allowed in most browsers, and appears to be
// relied upon by some libraries, like Bootstrap carousel
return;
}
if (!clock.timers) {
clock.timers = {};
}
// in Node, timerId is an object with .ref()/.unref(), and
// its .id field is the actual timer id.
if (typeof timerId === "object") {
timerId = timerId.id;
}
if (clock.timers.hasOwnProperty(timerId)) {
// check that the ID matches a timer of the correct type
var timer = clock.timers[timerId];
if (timer.type === ttype) {
delete clock.timers[timerId];
} else {
var clear = ttype === "AnimationFrame" ? "cancelAnimationFrame" : "clear" + ttype;
var schedule = timer.type === "AnimationFrame" ? "requestAnimationFrame" : "set" + timer.type;
throw new Error("Cannot clear timer: timer created with " + schedule
+ "() but cleared with " + clear + "()");
}
}
}
function uninstall(clock, target, config) {
var method,
i,
l;
var installedHrTime = "_hrtime";
var installedNextTick = "_nextTick";
for (i = 0, l = clock.methods.length; i < l; i++) {
method = clock.methods[i];
if (method === "hrtime" && target.process) {
target.process.hrtime = clock[installedHrTime];
} else if (method === "nextTick" && target.process) {
target.process.nextTick = clock[installedNextTick];
} else if (method === "performance") {
target[method] = clock["_" + method];
} else {
if (target[method] && target[method].hadOwnProperty) {
target[method] = clock["_" + method];
if (method === "clearInterval" && config.shouldAdvanceTime === true) {
target[method](clock.attachedInterval);
}
} else {
try {
delete target[method];
} catch (ignore) { /* eslint empty-block: "off" */ }
}
}
}
// Prevent multiple executions which will completely remove these props
clock.methods = [];
// return pending timers, to enable checking what timers remained on uninstall
if (!clock.timers) {
return [];
}
return Object.keys(clock.timers).map(function mapper(key) {
return clock.timers[key];
});
}
function hijackMethod(target, method, clock) {
var prop;
clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method);
clock["_" + method] = target[method];
if (method === "Date") {
var date = mirrorDateProperties(clock[method], target[method]);
target[method] = date;
} else if (method === "performance") {
target[method] = clock[method];
} else {
target[method] = function () {
return clock[method].apply(clock, arguments);
};
for (prop in clock[method]) {
if (clock[method].hasOwnProperty(prop)) {
target[method][prop] = clock[method][prop];
}
}
}
target[method].clock = clock;
}
function doIntervalTick(clock, advanceTimeDelta) {
clock.tick(advanceTimeDelta);
}
var timers = {
setTimeout: _global.setTimeout,
clearTimeout: _global.clearTimeout,
setImmediate: _global.setImmediate,
clearImmediate: _global.clearImmediate,
setInterval: _global.setInterval,
clearInterval: _global.clearInterval,
Date: _global.Date
};
if (hrtimePresent) {
timers.hrtime = _global.process.hrtime;
}
if (nextTickPresent) {
timers.nextTick = _global.process.nextTick;
}
if (performancePresent) {
timers.performance = _global.performance;
}
if (requestAnimationFramePresent) {
timers.requestAnimationFrame = _global.requestAnimationFrame;
}
if (queueMicrotaskPresent) {
timers.queueMicrotask = _global.queueMicrotask;
}
if (cancelAnimationFramePresent) {
timers.cancelAnimationFrame = _global.cancelAnimationFrame;
}
if (requestIdleCallbackPresent) {
timers.requestIdleCallback = _global.requestIdleCallback;
}
if (cancelIdleCallbackPresent) {
timers.cancelIdleCallback = _global.cancelIdleCallback;
}
var keys = Object.keys || function (obj) {
var ks = [];
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
ks.push(key);
}
}
return ks;
};
/**
* @param start {Date|number} the system time - non-integer values are floored
* @param loopLimit {number} maximum number of timers that will be run when calling runAll()
*/
function createClock(start, loopLimit) {
start = Math.floor(getEpoch(start));
loopLimit = loopLimit || 1000;
var nanos = 0;
var adjustedSystemTime = [0, 0]; // [millis, nanoremainder]
if (NativeDate === undefined) {
throw new Error("The global scope doesn't have a `Date` object"
+ " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)");
}
var clock = {
now: start,
timeouts: {},
Date: createDate(),
loopLimit: loopLimit
};
clock.Date.clock = clock;
function getTimeToNextFrame() {
return 16 - ((clock.now - start) % 16);
}
function hrtime(prev) {
var millisSinceStart = clock.now - adjustedSystemTime[0] - start;
var secsSinceStart = Math.floor( millisSinceStart / 1000);
var remainderInNanos = (millisSinceStart - secsSinceStart * 1e3 ) * 1e6 + nanos - adjustedSystemTime[1];
if (Array.isArray(prev)) {
if ( prev[1] > 1e9 ) {
throw new TypeError("Number of nanoseconds can't exceed a billion");
}
var oldSecs = prev[0];
var nanoDiff = remainderInNanos - prev[1];
var secDiff = secsSinceStart - oldSecs;
if (nanoDiff < 0) {
nanoDiff += 1e9;
secDiff -= 1;
}
return [secDiff, nanoDiff];
}
return [secsSinceStart, remainderInNanos];
}
clock.requestIdleCallback = function requestIdleCallback(func, timeout) {
var timeToNextIdlePeriod = 0;
if (clock.countTimers() > 0) {
timeToNextIdlePeriod = 50; // const for now
}
var result = addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 2),
delay: typeof timeout === "undefined" ? timeToNextIdlePeriod : Math.min(timeout, timeToNextIdlePeriod)
});
return result.id || result;
};
clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
return clearTimer(clock, timerId, "Timeout");
};
clock.setTimeout = function setTimeout(func, timeout) {
return addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 2),
delay: timeout
});
};
clock.clearTimeout = function clearTimeout(timerId) {
return clearTimer(clock, timerId, "Timeout");
};
clock.nextTick = function nextTick(func) {
return enqueueJob(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 1)
});
};
clock.queueMicrotask = function queueMicrotask(func) {
return clock.nextTick(func); // explicitly drop additional arguments
};
clock.setInterval = function setInterval(func, timeout) {
timeout = parseInt(timeout, 10);
return addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 2),
delay: timeout,
interval: timeout
});
};
clock.clearInterval = function clearInterval(timerId) {
return clearTimer(clock, timerId, "Interval");
};
clock.setImmediate = function setImmediate(func) {
return addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 1),
immediate: true
});
};
clock.clearImmediate = function clearImmediate(timerId) {
return clearTimer(clock, timerId, "Immediate");
};
clock.countTimers = function countTimers() {
return Object.keys(clock.timers || {}).length;
};
clock.requestAnimationFrame = function requestAnimationFrame(func) {
var result = addTimer(clock, {
func: func,
delay: getTimeToNextFrame(),
args: [clock.now + getTimeToNextFrame()],
animation: true
});
return result.id || result;
};
clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
return clearTimer(clock, timerId, "AnimationFrame");
};
clock.runMicrotasks = function runMicrotasks() {
runJobs(clock);
};
/**
* @param {tickValue} {String|Number} number of milliseconds or a human-readable value like "01:11:15"
*/
clock.tick = function tick(tickValue) {
var msFloat = typeof tickValue === "number" ? tickValue : parseTime(tickValue);
var ms = Math.floor(msFloat);
var remainder = nanoRemainder(msFloat);
var nanosTotal = nanos + remainder;
var tickTo = clock.now + ms;
if (msFloat < 0) {
throw new TypeError("Negative ticks are not supported");
}
// adjust for positive overflow
if (nanosTotal >= 1e6) {
tickTo += 1;
nanosTotal -= 1e6;
}
nanos = nanosTotal;
var tickFrom = clock.now;
var previous = clock.now;
var timer, firstException, oldNow;
clock.duringTick = true;
// perform microtasks
oldNow = clock.now;
runJobs(clock);
if (oldNow !== clock.now) {
// compensate for any setSystemTime() call during microtask callback
tickFrom += clock.now - oldNow;
tickTo += clock.now - oldNow;
}
// perform each timer in the requested range
timer = firstTimerInRange(clock, tickFrom, tickTo);
while (timer && tickFrom <= tickTo) {
if (clock.timers[timer.id]) {
tickFrom = timer.callAt;
clock.now = timer.callAt;
oldNow = clock.now;
try {
runJobs(clock);
callTimer(clock, timer);
} catch (e) {
firstException = firstException || e;
}
// compensate for any setSystemTime() call during timer callback
if (oldNow !== clock.now) {
tickFrom += clock.now - oldNow;
tickTo += clock.now - oldNow;
previous += clock.now - oldNow;
}
}
timer = firstTimerInRange(clock, previous, tickTo);
previous = tickFrom;
}
// perform process.nextTick()s again
oldNow = clock.now;
runJobs(clock);
if (oldNow !== clock.now) {
// compensate for any setSystemTime() call during process.nextTick() callback
tickFrom += clock.now - oldNow;
tickTo += clock.now - oldNow;
}
clock.duringTick = false;
// corner case: during runJobs, new timers were scheduled which could be in the range [clock.now, tickTo]
timer = firstTimerInRange(clock, tickFrom, tickTo);
if (timer) {
try {
clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range
} catch (e) {
firstException = firstException || e;
}
} else {
// no timers remaining in the requested range: move the clock all the way to the end
clock.now = tickTo;
// update nanos
nanos = nanosTotal;
}
if (firstException) {
throw firstException;
}
return clock.now;
};
clock.next = function next() {
runJobs(clock);
var timer = firstTimer(clock);
if (!timer) {
return clock.now;
}
clock.duringTick = true;
try {
clock.now = timer.callAt;
callTimer(clock, timer);
runJobs(clock);
return clock.now;
} finally {
clock.duringTick = false;
}
};
clock.runAll = function runAll() {
var numTimers, i;
runJobs(clock);
for (i = 0; i < clock.loopLimit; i++) {
if (!clock.timers) {
return clock.now;
}
numTimers = keys(clock.timers).length;
if (numTimers === 0) {
return clock.now;
}
clock.next();
}
throw new Error("Aborting after running " + clock.loopLimit + " timers, assuming an infinite loop!");
};
clock.runToFrame = function runToFrame() {
return clock.tick(getTimeToNextFrame());
};
clock.runToLast = function runToLast() {
var timer = lastTimer(clock);
if (!timer) {
runJobs(clock);
return clock.now;
}
return clock.tick(timer.callAt - clock.now);
};
clock.reset = function reset() {
nanos = 0;
clock.timers = {};
clock.jobs = [];
clock.now = start;
};
clock.setSystemTime = function setSystemTime(systemTime) {
// determine time difference
var newNow = getEpoch(systemTime);
var difference = newNow - clock.now;
var id, timer;
adjustedSystemTime[0] = difference;
adjustedSystemTime[1] = nanos;
// update 'system clock'
clock.now = newNow;
nanos = 0;
// update timers and intervals to keep them stable
for (id in clock.timers) {
if (clock.timers.hasOwnProperty(id)) {
timer = clock.timers[id];
timer.createdAt += difference;
timer.callAt += difference;
}
}
};
if (performancePresent) {
clock.performance = Object.create(null);
if (hasPerformancePrototype) {
var proto = _global.Performance.prototype;
Object
.getOwnPropertyNames(proto)
.forEach(function (name) {
clock.performance[name] = NOOP;
});
}
clock.performance.now = function lolexNow() {
var hrt = hrtime();
var millis = (hrt[0] * 1000 + hrt[1] / 1e6);
return millis;
};
}
if (hrtimePresent) {
clock.hrtime = hrtime;
}
return clock;
}
/**
* @param config {Object} optional config
* @param config.target {Object} the target to install timers in (default `window`)
* @param config.now {number|Date} a number (in milliseconds) or a Date object (default epoch)
* @param config.toFake {string[]} names of the methods that should be faked.
* @param config.loopLimit {number} the maximum number of timers that will be run when calling runAll()
* @param config.shouldAdvanceTime {Boolean} tells lolex to increment mocked time automatically (default false)
* @param config.advanceTimeDelta {Number} increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
*/
function install(config) {
if ( arguments.length > 1 || config instanceof Date || Array.isArray(config) || typeof config === "number") {
throw new TypeError("lolex.install called with " + String(config) +
" lolex 2.0+ requires an object parameter - see https://github.com/sinonjs/lolex");
}
config = typeof config !== "undefined" ? config : {};
config.shouldAdvanceTime = config.shouldAdvanceTime || false;
config.advanceTimeDelta = config.advanceTimeDelta || 20;
var i, l;
var target = config.target || _global;
var clock = createClock(config.now, config.loopLimit);
clock.uninstall = function () {
return uninstall(clock, target, config);
};
clock.methods = config.toFake || [];
if (clock.methods.length === 0) {
// do not fake nextTick by default - GitHub#126
clock.methods = keys(timers).filter(function (key) {return key !== "nextTick";});
}
for (i = 0, l = clock.methods.length; i < l; i++) {
if (clock.methods[i] === "hrtime") {
if (target.process && typeof target.process.hrtime === "function") {
hijackMethod(target.process, clock.methods[i], clock);
}
} else if (clock.methods[i] === "nextTick") {
if (target.process && typeof target.process.nextTick === "function") {
hijackMethod(target.process, clock.methods[i], clock);
}
} else {
if (clock.methods[i] === "setInterval" && config.shouldAdvanceTime === true) {
var intervalTick = doIntervalTick.bind(null, clock, config.advanceTimeDelta);
var intervalId = target[clock.methods[i]](
intervalTick,
config.advanceTimeDelta);
clock.attachedInterval = intervalId;
}
hijackMethod(target, clock.methods[i], clock);
}
}
return clock;
}
return {
timers: timers,
createClock: createClock,
install: install,
withGlobal: withGlobal
};
}
var defaultImplementation = withGlobal(global || window);
exports.timers = defaultImplementation.timers;
exports.createClock = defaultImplementation.createClock;
exports.install = defaultImplementation.install;
exports.withGlobal = withGlobal;