UNPKG

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