1
1
/* eslint-disable @lwc/lwc/no-async-await */
2
+ import { DeviceEventEmitter } from 'react-native' ;
2
3
import type { NetworkCacheEntry , NetworkCacheMap } from '@libs/E2E/types' ;
3
4
4
5
const LOG_TAG = `[E2E][NetworkInterceptor]` ;
@@ -93,6 +94,33 @@ function hashFetchArgs(args: Parameters<typeof fetch>) {
93
94
return `${ url } ${ JSON . stringify ( headers ) } ` ;
94
95
}
95
96
97
+ let activeRequestsCount = 0 ;
98
+
99
+ const ACTIVE_REQUESTS_QUEUE_IS_EMPTY_EVENT = 'activeRequestsQueueIsEmpty' ;
100
+
101
+ /**
102
+ * Assures that ongoing network requests are empty. **Highly desirable** to call this function before closing the app.
103
+ * Otherwise if some requests are persisted - they will be executed on the next app start. And it can lead to a situation
104
+ * where we can have `N * M` requests (where `N` is the number of app run per test and `M` is the number of test suites)
105
+ * and such big amount of requests can lead to a situation, where first app run (in test suite to cache network requests)
106
+ * may be blocked by spinners and lead to unbelievable big time execution, which eventually will be bigger than timeout and
107
+ * will lead to a test failure.
108
+ */
109
+ function waitForActiveRequestsToBeEmpty ( ) : Promise < void > {
110
+ console . debug ( 'Waiting for requests queue to be empty...' , activeRequestsCount ) ;
111
+
112
+ if ( activeRequestsCount === 0 ) {
113
+ return Promise . resolve ( ) ;
114
+ }
115
+
116
+ return new Promise ( ( resolve ) => {
117
+ const subscription = DeviceEventEmitter . addListener ( ACTIVE_REQUESTS_QUEUE_IS_EMPTY_EVENT , ( ) => {
118
+ subscription . remove ( ) ;
119
+ resolve ( ) ;
120
+ } ) ;
121
+ } ) ;
122
+ }
123
+
96
124
/**
97
125
* Install a network interceptor by overwriting the global fetch function:
98
126
* - Overwrites fetch globally with a custom implementation
@@ -145,6 +173,8 @@ export default function installNetworkInterceptor(
145
173
console . debug ( '!!! Missed cache hit for url:' , url ) ;
146
174
}
147
175
176
+ activeRequestsCount ++ ;
177
+
148
178
return originalFetch ( ...args )
149
179
. then ( async ( res ) => {
150
180
if ( networkCache != null ) {
@@ -166,6 +196,16 @@ export default function installNetworkInterceptor(
166
196
. then ( ( res ) => {
167
197
console . debug ( LOG_TAG , 'Network cache updated!' ) ;
168
198
return res ;
199
+ } )
200
+ . finally ( ( ) => {
201
+ console . debug ( 'Active requests count:' , activeRequestsCount ) ;
202
+
203
+ activeRequestsCount -- ;
204
+
205
+ if ( activeRequestsCount === 0 ) {
206
+ DeviceEventEmitter . emit ( ACTIVE_REQUESTS_QUEUE_IS_EMPTY_EVENT ) ;
207
+ }
169
208
} ) ;
170
209
} ;
171
210
}
211
+ export { waitForActiveRequestsToBeEmpty } ;
0 commit comments