-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclock.js
More file actions
197 lines (165 loc) · 5.87 KB
/
clock.js
File metadata and controls
197 lines (165 loc) · 5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// Copyright Titanium I.T. LLC.
import FakeTimers from "@sinonjs/fake-timers";
import * as ensure from "util/ensure.js";
const NOT_A_NULLED_CLOCK_MESSAGE = "Can't advance the clock because it isn't a nulled clock";
/** System clock, including time zone and locale. */
export class Clock {
/**
* Factory method. Wraps the system clock.
* @returns {Clock} the wrapped clock
*/
static create() {
ensure.signature(arguments, []);
return new Clock({
Date,
DateTimeFormat: Intl.DateTimeFormat,
setTimeout,
clearTimeout,
advanceNulledClockAsync() { throw new Error(NOT_A_NULLED_CLOCK_MESSAGE); },
advanceNulledClockUntilTimersExpireAsync() { throw new Error(NOT_A_NULLED_CLOCK_MESSAGE); }
});
}
/**
* Factory method. Creates a simulated system clock.
* @param [options] overridable options for the simulated clock
* @param [options.now] simulated current time
* @param [options.locale] computer's default locale
* @param [options.timeZone] computer's default time zone
* @returns {Clock} the simulated clock
*/
static createNull(options) {
return new Clock(stubbedGlobals(options));
}
/** Only for use by tests. (Use a factory method instead.) */
constructor(globals) {
ensure.signature(arguments, [ Object ]);
this._globals = globals;
}
/**
* @returns {number} the current time in milliseconds (equivalent to Date.now())
*/
now() {
ensure.signature(arguments, []);
return this._globals.Date.now();
}
/**
* Render the current date and/or time as a string.
* @param intlDateTimeFormatOptions Formatting options (see Intl.DateTimeFormatOptions); timeZone
* must be specified (use 'local' for computer's time zone)
* @param locale Locale to use for localization (use 'local' for computer's default locale)
* @returns {string} the formatted date/time
*/
toFormattedString(intlDateTimeFormatOptions, locale) {
if (intlDateTimeFormatOptions?.timeZone === undefined) {
throw new Error("Must specify options.timeZone (use 'local' for computer's time zone)");
}
if (locale === undefined) {
throw new Error("Must specify locale (use 'local' for computer's default locale)");
}
ensure.signature(arguments, [ Object, String ]);
const options = { ...intlDateTimeFormatOptions };
if (options.timeZone === "local") delete options.timeZone;
if (locale === "local") locale = undefined;
const now = new this._globals.Date();
const formatter = this._globals.DateTimeFormat(locale, options);
return formatter.format(now);
}
/**
* Advance a nulled clock forward in time. Throws an exception if the clock isn't nulled. (For
* non-nulled clocks, use waitAsync() instead.)
* @param milliseconds the number of milliseconds to advance the clock
*/
async advanceNulledClockAsync(milliseconds) {
ensure.signature(arguments, [ Number ]);
await this._globals.advanceNulledClockAsync(milliseconds);
}
/**
* Advance a nulled clock forward in time until all timers expire. Throws an exception if the
* clock isn't nulled.
* @returns {Promise<void>}
*/
async advanceNulledClockUntilTimersExpireAsync() {
ensure.signature(arguments, []);
await this._globals.advanceNulledClockUntilTimersExpireAsync();
}
/**
* Wait for a certain amount of time has passed. Equivalent to setTimeout(), which is not guaranteed
* to be exact. Special note for nulled clocks: time doesn't pass automatically for nulled clocks, so
* this method won't return unless one of the advanceNulledClock methods is called.
* @param milliseconds the approximate number of milliseconds to wait
*/
async waitAsync(milliseconds) {
ensure.signature(arguments, [ Number ]);
await new Promise((resolve) => {
this._globals.setTimeout(resolve, milliseconds);
});
}
/**
* Wait for a promise to resolve and return its value. If it hasn't completed in a certain amount
* of time, run a timeout function and return its value instead. Note that this DOES NOT CANCEL
* the original promise, which will still run to completion, although its return value will be
* discarded. (Promises cannot be cancelled.) Any cancellation mechanism you want to use must be
* programmed into the promise and timeout function.
* @param milliseconds the approximate number of milliseconds to wait
* @param promiseToWaitFor the promise to wait for
* @param timeoutFnAsync the function to run when the time is up
* @returns {Promise<unknown>} the promise's return value (if the promise resolves in time) or the
* timeout function's return value (if it doesn't)
*/
async timeoutAsync(milliseconds, promiseToWaitFor, timeoutFnAsync) {
ensure.signature(arguments, [ Number, Promise, Function ]);
return await new Promise(async (resolve, reject) => {
const cancelToken = this._globals.setTimeout(async () => {
try {
const result = await timeoutFnAsync();
resolve(result);
}
catch (err) {
reject(err);
}
}, milliseconds);
try {
const result = await promiseToWaitFor;
resolve(result);
}
catch (err) {
reject(err);
}
finally {
this._globals.clearTimeout(cancelToken);
}
});
}
}
function stubbedGlobals({
now = 0,
locale = "gv-GB",
timeZone = "Australia/Lord_Howe"
} = {}) {
ensure.signature(arguments, [[ undefined, {
now: [ undefined, Number ],
locale: [ undefined, String ],
timeZone: [ undefined, String ],
}]]);
const fake = FakeTimers.createClock(now);
return {
Date: fake.Date,
DateTimeFormat(locales, options) {
if (locales === undefined) locales = locale;
options = { timeZone, ...options };
return Intl.DateTimeFormat(locales, options);
},
async advanceNulledClockAsync(milliseconds) {
await fake.tickAsync(milliseconds);
},
async advanceNulledClockUntilTimersExpireAsync() {
await fake.runAllAsync();
},
setTimeout(fn, milliseconds) {
return fake.setTimeout(fn, milliseconds);
},
clearTimeout(fn, milliseconds) {
return fake.clearTimeout(fn, milliseconds);
},
};
}