UNPKG

1.21 kBPlain TextView Raw
1import lolex from 'lolex';
2
3export default class Clock {
4 private isUsingMockClock = false;
5 private mockClock?: lolex.Clock;
6
7 mock(now: number | Date = Date.now()) {
8 if (this.isUsingMockClock) {
9 throw new Error(
10 'The clock is already mocked, but you tried to mock it again.',
11 );
12 }
13
14 this.isUsingMockClock = true;
15 this.mockClock = lolex.install({now});
16 }
17
18 restore() {
19 if (!this.isUsingMockClock) {
20 throw new Error(
21 'The clock is already real, but you tried to restore it again.',
22 );
23 }
24
25 this.isUsingMockClock = false;
26
27 if (this.mockClock) {
28 this.mockClock.uninstall();
29 delete this.mockClock;
30 }
31 }
32
33 isMocked() {
34 return this.isUsingMockClock;
35 }
36
37 tick(time: number) {
38 this.ensureClockIsMocked();
39 if (this.mockClock) {
40 this.mockClock.tick(time);
41 }
42 }
43
44 setTime(time: number | Date) {
45 this.ensureClockIsMocked();
46 if (this.mockClock) {
47 this.mockClock.setSystemTime(time);
48 }
49 }
50
51 private ensureClockIsMocked() {
52 if (!this.isUsingMockClock) {
53 throw new Error(
54 'You must call clock.mock() before interacting with the mock clock.',
55 );
56 }
57 }
58}