Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
The lolex npm package is a library for JavaScript that allows you to control and manipulate the passage of time. It can be particularly useful in testing environments where you want to simulate specific timing conditions without waiting for real time to pass. It allows you to mock the Date object, timers like setTimeout, setInterval, and setImmediate, as well as nextTick (in Node.js). This can help in creating deterministic tests for time-dependent code.
Mocking Date
This feature allows you to mock the global Date object, so you can simulate any time you need for testing purposes.
const lolex = require('lolex');
const clock = lolex.install();
console.log(new Date()); // This will show the mocked date
clock.uninstall();
Timers
With lolex, you can simulate the behavior of JavaScript timers (setTimeout, setInterval, and setImmediate), allowing you to test timer-dependent code without real time delays.
const lolex = require('lolex');
const clock = lolex.install();
setTimeout(() => console.log('Timer called'), 1000);
clock.tick(1000); // Manually advance the clock
// 'Timer called' is printed to the console
clock.uninstall();
nextTick
This feature is specific to Node.js and allows you to control the process.nextTick queue, enabling the testing of code that uses nextTick to defer actions.
const lolex = require('lolex');
const clock = lolex.install({toFake: ['nextTick']});
process.nextTick(() => console.log('nextTick called'));
clock.runAll(); // Executes all scheduled nextTick callbacks
clock.uninstall();
Sinon is a testing utility that includes spies, mocks, and stubs, but also features a powerful fake timers system similar to lolex. In fact, lolex is a part of Sinon for handling time-related functionalities. Sinon's fake timers can be used independently of its spying and mocking capabilities, making it a versatile choice for testing time-dependent code.
Timekeeper is a simpler alternative focused solely on mocking the Date object and controlling time in tests. It doesn't offer the extensive timer manipulation features of lolex, such as mocking setTimeout or setInterval, but it's lightweight and easy to use for tests that only need to manipulate the system clock.
Jest, a popular testing framework, includes jest-fake-timers, which provides functionality to mock timers within Jest tests. It offers similar features to lolex, allowing you to advance timers manually and control the JavaScript event loop. It's tightly integrated with Jest, making it a convenient option for projects already using Jest for testing.
JavaScript implementation of the timer APIs; setTimeout
, clearTimeout
,
setImmediate
, clearImmediate
, setInterval
and clearInterval
, along with
a clock instance that controls the flow of time. Lolex also provides a Date
implementation that gets its time from 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. Lolex is extracted from Sinon.JS.
Lolex can be installed using npm
:
npm install lolex
If you want to use Lolex in a browser, you have a few options. Releases are hosted on the sinonjs.org website. You can also get the node module and build a file for the browser using browserify:
npm install lolex
npm install browserify # If you don't already have it globally installed
browserify node_modules/lolex/lolex.js
To use lolex, create a new clock, schedule events on it using the timer
functions and pass time using the tick
method.
// 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 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
, and runToLast
methods are available to advance the clock. See the
API Reference for more details.
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.
// 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.
var lolex = require("lolex");
var context = {
setTimeout: setTimeout // By default context.setTimeout uses the global setTimeout
}
var clock = lolex.install(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.
var clock = lolex.createClock([now[, loopLimit]])
Creates a clock. The default
epoch 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([context[, now[, toFake[, loopLimit]]]])
var clock = lolex.install([now[, toFake[, loopLimit]]])
Creates a clock and installs it onto the context
object, or globally. The
now
argument is the same as in lolex.createClock()
.
toFake
is an array of the names of the methods that should be faked. You can
pick from setTimeout
, clearTimeout
, setImmediate
, clearImmediate
,
setInterval
, clearInterval
, and Date
. E.g. lolex.install(["setTimeout", "clearTimeout"])
.
The loopLimit
argument is the same as in lolex.createClock()
.
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.hrtime(prevTime?)
Only available in Node.JS, mimicks process.hrtime().
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.
time
may be negative, which causes the clock to change but won't fire any
callbacks.
clock.next()
Advances the clock to the the moment of the first scheduled timer, firing 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.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 context
that was passed to
lolex.install
, or the native timers if no context
was given.
Date
Implements the Date
object but using the clock to provide the correct time.
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.
npm test
Or, if you prefer more verbose output:
$(npm bin)/mocha ./test/lolex-test.js
Mochify is used to run the tests in
PhantomJS. Make sure you have phantomjs
installed. Then:
npm test-headless
BSD 3-clause "New" or "Revised" License (see LICENSE file)
FAQs
Fake JavaScript timers
The npm package lolex receives a total of 3,187,494 weekly downloads. As such, lolex popularity was classified as popular.
We found that lolex demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.