UNPKG

@serenity-js/core

Version:

The core Serenity/JS framework, providing the Screenplay Pattern interfaces, as well as the test reporting and integration infrastructure

77 lines 2.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Clock = void 0; const tiny_types_1 = require("tiny-types"); const Duration_1 = require("./Duration"); const Timestamp_1 = require("./Timestamp"); /** * A [`Clock`](https://serenity-js.org/api/core/class/Clock/) tells the time. This abstraction allows Serenity/JS to have a single place * in the framework responsible for telling the time, and one that can be easily mocked for internal testing. * * ```ts * const now: Timestamp = new Clock().now() * ``` * * ## Learn more * - [`Timestamp`](https://serenity-js.org/api/core/class/Timestamp/) * - [`Duration`](https://serenity-js.org/api/core/class/Duration/) * * @group Time */ class Clock { checkTime; static resolution = Duration_1.Duration.ofMilliseconds(10); timeAdjustment = Duration_1.Duration.ofMilliseconds(0); constructor(checkTime = () => new Date()) { this.checkTime = checkTime; } toJSON() { return { timeAdjustment: this.timeAdjustment.toJSON(), }; } /** * Sets the clock ahead to force early resolution of promises * returned by [`Clock.waitFor`](https://serenity-js.org/api/core/class/Clock/#waitFor). * * Useful for test purposes to avoid unnecessary delays. * * @param duration */ setAhead(duration) { this.timeAdjustment = (0, tiny_types_1.ensure)('duration', duration, (0, tiny_types_1.isDefined)()); } /** * Returns a Promise that resolves after one tick of the clock. * * Useful for test purposes to avoid unnecessary delays. */ async tick() { return new Promise(resolve => setTimeout(resolve, Clock.resolution.inMilliseconds())); } /** * Returns current time */ now() { return new Timestamp_1.Timestamp(this.checkTime()).plus(this.timeAdjustment); } /** * Returns a Promise that will be resolved after the given duration * * @param duration */ async waitFor(duration) { const stopAt = this.now().plus(duration); let timer; return new Promise(resolve => { timer = setInterval(() => { if (this.now().isAfterOrEqual(stopAt)) { clearInterval(timer); return resolve(); } }, Clock.resolution.inMilliseconds()); }); } } exports.Clock = Clock; //# sourceMappingURL=Clock.js.map