UNPKG

953 BPlain TextView Raw
1export default class Timer {
2 private isUsingFakeTimers = false;
3
4 mock() {
5 if (this.isUsingFakeTimers) {
6 throw new Error(
7 'The Timer is already mocked, but you tried to mock it again.',
8 );
9 }
10
11 jest.useFakeTimers();
12 this.isUsingFakeTimers = true;
13 }
14
15 restore() {
16 if (!this.isUsingFakeTimers) {
17 throw new Error(
18 'The Timer is already real, but you tried to restore it again.',
19 );
20 }
21
22 jest.useRealTimers();
23 this.isUsingFakeTimers = false;
24 }
25
26 isMocked() {
27 return this.isUsingFakeTimers;
28 }
29
30 runAllTimers() {
31 this.ensureUsingFakeTimers();
32 jest.runAllTimers();
33 }
34
35 runTimersToTime(time: number) {
36 this.ensureUsingFakeTimers();
37 jest.runTimersToTime(time);
38 }
39
40 private ensureUsingFakeTimers() {
41 if (!this.isUsingFakeTimers) {
42 throw new Error(
43 'You must call Timer.mock() before interacting with the mock Timer.',
44 );
45 }
46 }
47}