1+ /**
2+ * @license
3+ * Copyright Google Inc. All Rights Reserved.
4+ *
5+ * Use of this source code is governed by an MIT-style license that can be
6+ * found in the LICENSE file at https://angular.io/license
7+ */
8+ export function addJestTimer ( jest : any , global : any ) {
9+ const { resetFakeAsyncZone, flushMicrotasks, discardPeriodicTasks, tick, flush, fakeAsync} =
10+ ( Zone as any ) [ Zone . __symbol__ ( 'fakeAsyncTest' ) ] ;
11+ const FakeAsyncTestZoneSpec = ( Zone as any ) [ 'FakeAsyncTestZoneSpec' ] ;
12+ const ProxyZoneSpec = ( Zone as any ) [ 'ProxyZoneSpec' ] ;
13+
14+ function getFakeAsyncTestZoneSpec ( ) {
15+ return Zone . current . get ( 'FakeAsyncTestZoneSpec' ) ;
16+ }
17+
18+ jest . clearAllTimers = function ( ) {
19+ const zs = getFakeAsyncTestZoneSpec ( ) ;
20+ if ( ! zs ) {
21+ return ;
22+ }
23+ // TODO: @JiaLiPassion , add clear method in fakeAsyncZoneSpec
24+ // flush();
25+ } ;
26+
27+ jest . runAllTimers = function ( ) {
28+ const zs = getFakeAsyncTestZoneSpec ( ) ;
29+ if ( ! zs ) {
30+ return ;
31+ }
32+ // TODO: @JiaLiPassion , now flush can only flush
33+ // non periodic timers, should flush periodic too.
34+ flush ( ) ;
35+ } ;
36+
37+ jest . runAllImmediates = function ( ) {
38+ const zs = getFakeAsyncTestZoneSpec ( ) ;
39+ if ( ! zs ) {
40+ return ;
41+ }
42+ // TODO: @JiaLiPassion , should we support this one?
43+ flush ( ) ;
44+ } ;
45+
46+ jest . runOnlyPendingTimers = function ( ) {
47+ const zs = getFakeAsyncTestZoneSpec ( ) ;
48+ if ( ! zs ) {
49+ return ;
50+ }
51+ // TODO: @JiaLiPassion , should we support this one?
52+ flush ( ) ;
53+ } ;
54+
55+ jest . advanceTimersByTime = function ( msToRun : number ) {
56+ const zs = getFakeAsyncTestZoneSpec ( ) ;
57+ if ( ! zs ) {
58+ return ;
59+ }
60+ tick ( msToRun ) ;
61+ } ;
62+
63+
64+ jest . runAllTicks = function ( ) {
65+ const zs = getFakeAsyncTestZoneSpec ( ) ;
66+ if ( ! zs ) {
67+ return ;
68+ }
69+ flushMicrotasks ( ) ;
70+ } ;
71+
72+ jest . useFakeTimers = function ( ) {
73+ const zs = getFakeAsyncTestZoneSpec ( ) ;
74+ if ( zs ) {
75+ return ;
76+ }
77+ const fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec ( )
78+ const proxyZoneSpec = ProxyZoneSpec . get ( ) ;
79+ jest . __zone_symbol__last_delegate_spec = proxyZoneSpec . getDelegate ( ) ;
80+ proxyZoneSpec . setDelegate ( fakeAsyncTestZoneSpec ) ;
81+ fakeAsyncTestZoneSpec . lockDatePatch ( ) ;
82+ } ;
83+
84+ jest . useRealTimers = function ( ) {
85+ const zs = getFakeAsyncTestZoneSpec ( ) ;
86+ if ( ! zs ) {
87+ throw new Error ( 'Must use real timers in the same block with useFakeTimers' ) ;
88+ }
89+ const proxyZoneSpec = ProxyZoneSpec . get ( ) ;
90+ const lastDelegate = jest . __zone_symbol__last_delegate_spec ;
91+ jest . __zone_symbol__last_delegate_spec = null ;
92+ proxyZoneSpec . setDelegate ( lastDelegate ) ;
93+ zs . unlockDatePatch ( ) ;
94+ }
95+ }
0 commit comments