UNPKG

mockzilla

Version:

A mocking toolkit leveraging the power of TypeScript to enhance your jest experience.

48 lines (47 loc) 1.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mockTime = exports.advanceTime = void 0; const error_1 = require("./error"); let currentTime = 0; let timeouts = []; // fixme: remember stack in order to show the invocation afterwards const setTimeout = (callback, ms) => { const entry = { start: currentTime + ms, callback, }; timeouts.push(entry); return entry; }; const clearTimeout = (entry) => { const index = timeouts.indexOf(entry); if (index >= 0) timeouts.splice(index, 1); }; function advanceTime(ms) { currentTime += ms; const remaining = []; const expired = []; for (const entry of timeouts) { if (entry.start <= currentTime) expired.push(entry); else remaining.push(entry); } timeouts = remaining; expired.sort((a, b) => a.start - b.start).forEach((e) => e.callback()); } exports.advanceTime = advanceTime; function mockTime() { global.setTimeout = setTimeout; global.clearTimeout = clearTimeout; beforeEach(() => { timeouts = []; currentTime = 0; }); afterEach(() => { if (timeouts.length !== 0) throw new error_1.MockzillaError(`${timeouts.length} timeouts still active after test has finished`, true); }); } exports.mockTime = mockTime;