Home

Awesome

clock-mock

A mock clock for tests involving timing.

Don't just use setTimeout() and hope that the timings work out. This makes tests take forever and be non-deterministic and flaky.

Instead, mock the clock, and explicitly advance it so you can test timing issues precisely and deterministically.

USAGE

import { Clock } from 'clock-mock'
// this also works:
// const { Clock } = require('clock-mock')

import t from 'tap' // or whatever you use

// the module you wrote that does timing stuff
import { myModuleThatDoesStuffWithTime } from '../index.js'

t.test('test timeouts precisely', t => {
  const c = new Clock()
  c.enter()
  myModuleThatDoesStuffWithTime.scheduleThing('foo', 100)
  c.advance(99)
  t.equal(myModuleThatDoesStuffWithTime.thingRan('foo'), false)
  c.advance(1) // the timeout fired!
  t.equal(myModuleThatDoesStuffWithTime.thingRan('foo'), true)

  c.exit()
  t.end()
})

Patches:

API