Skip to content
Easily manipulate and mock out time in your tests
JavaScript HTML
Find file
Latest commit 0011f8f @Raynos Raynos 0.1.4
Failed to load latest commit information.
examples initial
test add clearTimeout support
.gitignore initial
.npmignore initial
.testem.json initial
.travis.yml initial
LICENCE initial docs
index.js Start timer counter at 1 instead of 0
package.json 0.1.4


build status

browser support

Easily manipulate and mock out time in your tests


Let's say you have a simple time module that collects an array of timestamps every second.

// ./fixtures/time.js
var setTimeout = require("timers").setTimeout
var now = require("date-now")

module.exports = function () {
    var items = []


    return peek

    function peek() {
        return items

    function loop() {

        setTimeout(loop, 1000)

It uses require("timers").setTimeout and require("date-now") so that it's not hardcoded to time based global state.

We can then simply mock these things out using mock

var mock = require("mock")
var assert = require("assert")

var Timer = require("../index")

// Pass starting time to Timer
var timer = Timer(0)

// Pass mocked setTimeout and functions to your module
var time = mock("./fixtures/time", {
    timers: {
        setTimeout: timer.setTimeout
    , "date-now":
}, require)

var t = time()

console.log("#1", t())
assert.deepEqual(t(), [ 0 ])


console.log("#2", t())
assert.deepEqual(t(), [ 0 ])


console.log("#3", t())
assert.deepEqual(t(), [ 0, 1000 ])


console.log("#4", t())
assert.deepEqual(t(), [ 0, 1000, 2000, 3000 ])


console.log("#5", t())
assert.deepEqual(t(), [ 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000 ])

Timer basically allows you to create simple mockable functions for setTimeout and You can then call timer.advance(delta) to make time move forward.

This is awesome for unit tests when you don't want your tests to be slow based on the fact that they have to wait for timeouts.


npm install time-mock


  • Raynos

MIT Licenced

Something went wrong with that request. Please try again.