@datadog/mobile-react-native 1.0.0-rc3 → 1.0.0-rc6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/DatadogSDKReactNative.podspec +1 -1
  2. package/README.md +47 -16
  3. package/android/build.gradle +2 -3
  4. package/android/gradle.properties +4 -4
  5. package/android/src/main/java/com/datadog/reactnative/DdRum.kt +25 -24
  6. package/android/src/main/java/com/datadog/reactnative/DdTrace.kt +6 -6
  7. package/ios/Sources/DdRum.m +10 -9
  8. package/ios/Sources/DdRum.swift +24 -24
  9. package/ios/Sources/DdTrace.m +2 -2
  10. package/ios/Sources/DdTrace.swift +6 -6
  11. package/lib/commonjs/DdSdkReactNative.js +42 -22
  12. package/lib/commonjs/DdSdkReactNative.js.map +1 -1
  13. package/lib/commonjs/DdSdkReactNativeConfiguration.js +17 -2
  14. package/lib/commonjs/DdSdkReactNativeConfiguration.js.map +1 -1
  15. package/lib/commonjs/InternalLog.js +51 -0
  16. package/lib/commonjs/InternalLog.js.map +1 -0
  17. package/lib/commonjs/ProxyConfiguration.js.map +1 -1
  18. package/lib/commonjs/SdkVerbosity.js +26 -0
  19. package/lib/commonjs/SdkVerbosity.js.map +1 -0
  20. package/lib/commonjs/TimeProvider.js +72 -0
  21. package/lib/commonjs/TimeProvider.js.map +1 -0
  22. package/lib/commonjs/Timer.js +10 -23
  23. package/lib/commonjs/Timer.js.map +1 -1
  24. package/lib/commonjs/TrackingConsent.js.map +1 -1
  25. package/lib/commonjs/foundation.js +62 -40
  26. package/lib/commonjs/foundation.js.map +1 -1
  27. package/lib/commonjs/index.js +26 -18
  28. package/lib/commonjs/index.js.map +1 -1
  29. package/lib/commonjs/internal.js +14 -0
  30. package/lib/commonjs/internal.js.map +1 -0
  31. package/lib/commonjs/rum/instrumentation/DdEventsInterceptor.js +14 -5
  32. package/lib/commonjs/rum/instrumentation/DdEventsInterceptor.js.map +1 -1
  33. package/lib/commonjs/rum/instrumentation/DdRumErrorTracking.js +51 -20
  34. package/lib/commonjs/rum/instrumentation/DdRumErrorTracking.js.map +1 -1
  35. package/lib/commonjs/rum/instrumentation/DdRumResourceTracking.js +141 -30
  36. package/lib/commonjs/rum/instrumentation/DdRumResourceTracking.js.map +1 -1
  37. package/lib/commonjs/rum/instrumentation/DdRumUserInteractionTracking.js +46 -7
  38. package/lib/commonjs/rum/instrumentation/DdRumUserInteractionTracking.js.map +1 -1
  39. package/lib/commonjs/rum/instrumentation/NoOpEventsInterceptor.js.map +1 -1
  40. package/lib/commonjs/rum/instrumentation/ShallowObjectEqualityChecker.js +34 -0
  41. package/lib/commonjs/rum/instrumentation/ShallowObjectEqualityChecker.js.map +1 -0
  42. package/lib/commonjs/rum/instrumentation/TraceIdentifier.js.map +1 -1
  43. package/lib/commonjs/types.js.map +1 -1
  44. package/lib/commonjs/version.js +10 -0
  45. package/lib/commonjs/version.js.map +1 -0
  46. package/lib/module/DdSdkReactNative.js +34 -22
  47. package/lib/module/DdSdkReactNative.js.map +1 -1
  48. package/lib/module/DdSdkReactNativeConfiguration.js +18 -3
  49. package/lib/module/DdSdkReactNativeConfiguration.js.map +1 -1
  50. package/lib/module/InternalLog.js +46 -0
  51. package/lib/module/InternalLog.js.map +1 -0
  52. package/lib/module/ProxyConfiguration.js.map +1 -1
  53. package/lib/module/SdkVerbosity.js +18 -0
  54. package/lib/module/SdkVerbosity.js.map +1 -0
  55. package/lib/module/TimeProvider.js +63 -0
  56. package/lib/module/TimeProvider.js.map +1 -0
  57. package/lib/module/Timer.js +14 -23
  58. package/lib/module/Timer.js.map +1 -1
  59. package/lib/module/TrackingConsent.js.map +1 -1
  60. package/lib/module/foundation.js +42 -40
  61. package/lib/module/foundation.js.map +1 -1
  62. package/lib/module/index.js +3 -2
  63. package/lib/module/index.js.map +1 -1
  64. package/lib/module/internal.js +2 -0
  65. package/lib/module/internal.js.map +1 -0
  66. package/lib/module/rum/instrumentation/DdEventsInterceptor.js +11 -5
  67. package/lib/module/rum/instrumentation/DdEventsInterceptor.js.map +1 -1
  68. package/lib/module/rum/instrumentation/DdRumErrorTracking.js +46 -20
  69. package/lib/module/rum/instrumentation/DdRumErrorTracking.js.map +1 -1
  70. package/lib/module/rum/instrumentation/DdRumResourceTracking.js +133 -29
  71. package/lib/module/rum/instrumentation/DdRumResourceTracking.js.map +1 -1
  72. package/lib/module/rum/instrumentation/DdRumUserInteractionTracking.js +41 -6
  73. package/lib/module/rum/instrumentation/DdRumUserInteractionTracking.js.map +1 -1
  74. package/lib/module/rum/instrumentation/NoOpEventsInterceptor.js.map +1 -1
  75. package/lib/module/rum/instrumentation/ShallowObjectEqualityChecker.js +25 -0
  76. package/lib/module/rum/instrumentation/ShallowObjectEqualityChecker.js.map +1 -0
  77. package/lib/module/rum/instrumentation/TraceIdentifier.js.map +1 -1
  78. package/lib/module/types.js.map +1 -1
  79. package/lib/module/version.js +3 -0
  80. package/lib/module/version.js.map +1 -0
  81. package/lib/typescript/DdSdkReactNative.d.ts +7 -6
  82. package/lib/typescript/DdSdkReactNativeConfiguration.d.ts +15 -4
  83. package/lib/typescript/InternalLog.d.ts +6 -0
  84. package/lib/typescript/SdkVerbosity.d.ts +9 -0
  85. package/lib/typescript/TimeProvider.d.ts +20 -0
  86. package/lib/typescript/Timer.d.ts +3 -2
  87. package/lib/typescript/index.d.ts +3 -2
  88. package/lib/typescript/internal.d.ts +1 -0
  89. package/lib/typescript/rum/instrumentation/DdEventsInterceptor.d.ts +1 -0
  90. package/lib/typescript/rum/instrumentation/DdRumErrorTracking.d.ts +3 -2
  91. package/lib/typescript/rum/instrumentation/DdRumResourceTracking.d.ts +13 -8
  92. package/lib/typescript/rum/instrumentation/DdRumUserInteractionTracking.d.ts +3 -3
  93. package/lib/typescript/rum/instrumentation/DdRumXhr.d.ts +13 -3
  94. package/lib/typescript/rum/instrumentation/ShallowObjectEqualityChecker.d.ts +4 -0
  95. package/lib/typescript/types.d.ts +12 -11
  96. package/lib/typescript/version.d.ts +1 -0
  97. package/package.json +7 -4
  98. package/src/DdSdkReactNative.tsx +112 -58
  99. package/src/DdSdkReactNativeConfiguration.tsx +22 -14
  100. package/src/InternalLog.tsx +45 -0
  101. package/src/ProxyConfiguration.tsx +5 -5
  102. package/src/{NativeSdkVerbosity.tsx → SdkVerbosity.tsx} +6 -6
  103. package/src/TimeProvider.tsx +64 -0
  104. package/src/Timer.ts +20 -35
  105. package/src/TrackingConsent.tsx +3 -3
  106. package/src/__mocks__/InternalLog.tsx +9 -0
  107. package/src/__tests__/DdRumWrapper.test.tsx +98 -0
  108. package/src/__tests__/DdSdkReactNative.test.tsx +699 -500
  109. package/src/__tests__/InternalLog.test.tsx +379 -0
  110. package/src/__tests__/TimeProvider.test.tsx +75 -0
  111. package/src/__tests__/Timer.test.ts +148 -57
  112. package/src/__tests__/rum/instrumentation/DdEventsInterceptor.test.tsx +151 -92
  113. package/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx +243 -76
  114. package/src/__tests__/rum/instrumentation/DdRumResourceTracking.test.tsx +723 -403
  115. package/src/__tests__/rum/instrumentation/DdRumUserInteractionTracking.test.tsx +239 -85
  116. package/src/__tests__/rum/instrumentation/ShallowObjectEqualityChecker.test.ts +31 -0
  117. package/src/__tests__/rum/instrumentation/TraceIdentifier.test.tsx +13 -15
  118. package/src/__tests__/rum/instrumentation/__utils__/XMLHttpRequestMock.ts +97 -0
  119. package/src/foundation.tsx +55 -42
  120. package/src/index.tsx +13 -3
  121. package/src/internal.tsx +1 -0
  122. package/src/rum/instrumentation/DdEventsInterceptor.tsx +51 -35
  123. package/src/rum/instrumentation/DdRumErrorTracking.tsx +75 -42
  124. package/src/rum/instrumentation/DdRumResourceTracking.tsx +312 -166
  125. package/src/rum/instrumentation/DdRumUserInteractionTracking.tsx +72 -25
  126. package/src/rum/instrumentation/DdRumXhr.tsx +21 -11
  127. package/src/rum/instrumentation/EventsInterceptor.tsx +3 -3
  128. package/src/rum/instrumentation/NoOpEventsInterceptor.tsx +2 -2
  129. package/src/rum/instrumentation/ShallowObjectEqualityChecker.ts +24 -0
  130. package/src/rum/instrumentation/TraceIdentifier.tsx +19 -19
  131. package/src/types.tsx +199 -157
  132. package/src/version.ts +2 -0
  133. package/lib/commonjs/NativeSdkVerbosity.js +0 -26
  134. package/lib/commonjs/NativeSdkVerbosity.js.map +0 -1
  135. package/lib/module/NativeSdkVerbosity.js +0 -18
  136. package/lib/module/NativeSdkVerbosity.js.map +0 -1
  137. package/lib/typescript/NativeSdkVerbosity.d.ts +0 -9
@@ -4,76 +4,34 @@
4
4
  * Copyright 2016-Present Datadog, Inc.
5
5
  */
6
6
 
7
- import { DdRumResourceTracking, PARENT_ID_HEADER_KEY, TRACE_ID_HEADER_KEY, ORIGIN_RUM, ORIGIN_HEADER_KEY } from '../../../rum/instrumentation/DdRumResourceTracking'
8
- import { DdRum } from '../../../index';
9
- import { Platform } from 'react-native';
10
-
11
- jest.useFakeTimers()
12
-
13
- jest.mock('../../../foundation', () => {
14
- return {
15
- DdRum: {
16
- startResource: jest.fn().mockResolvedValue(() => {
17
- return Promise.resolve()
18
- }),
19
-
20
- stopResource: jest.fn().mockResolvedValue(() => {
21
- return Promise.resolve()
22
- })
23
- },
24
- };
25
- });
26
-
27
- class XMLHttpRequest {
28
-
29
- static readonly UNSENT = 0;
30
- static readonly OPENED = 1;
31
- static readonly HEADERS_RECEIVED = 2;
32
- static readonly LOADING = 3;
33
- static readonly DONE = 4;
34
-
35
- public response: string | undefined = undefined
36
- public status: number | undefined = undefined
37
- public readyState: number = XMLHttpRequest.UNSENT
38
- public headers: Map<String, String> = new Map()
39
-
40
- constructor() {
41
-
42
- }
43
-
44
- public originalOpenCalled: boolean = false
45
- public originalSendCalled: boolean = false
46
- public originalOnReadyStateChangeCalled: boolean = false
47
-
48
- open(method: string, url: string) {
49
- this.originalOpenCalled = true;
50
- }
51
- send() {
52
- this.originalSendCalled = true;
53
- }
54
- onreadystatechange() {
55
- this.originalOnReadyStateChangeCalled = true
56
- }
57
-
58
- abort() {
59
- this.status = 0
60
- }
61
-
62
- notifyResponseArrived() {
63
- this.readyState = XMLHttpRequest.HEADERS_RECEIVED
64
- this.onreadystatechange()
65
- }
66
-
67
- complete(status: number, response?: string) {
68
- this.response = response
69
- this.status = status
70
- this.readyState = XMLHttpRequest.DONE
71
- this.onreadystatechange()
72
- }
73
-
74
- setRequestHeader(header: string, value: string): void {
75
- this.headers[header] = value
76
- }
7
+ import { Platform, NativeModules } from 'react-native';
8
+
9
+ import { InternalLog } from '../../../InternalLog';
10
+ import { SdkVerbosity } from '../../../SdkVerbosity';
11
+ import {
12
+ DdRumResourceTracking,
13
+ PARENT_ID_HEADER_KEY,
14
+ TRACE_ID_HEADER_KEY,
15
+ ORIGIN_RUM,
16
+ ORIGIN_HEADER_KEY,
17
+ SAMPLING_PRIORITY_HEADER_KEY,
18
+ calculateResponseSize,
19
+ RESOURCE_SIZE_ERROR_MESSAGE
20
+ } from '../../../rum/instrumentation/DdRumResourceTracking';
21
+
22
+ import { XMLHttpRequestMock } from './__utils__/XMLHttpRequestMock';
23
+
24
+ jest.useFakeTimers();
25
+ jest.mock('../../../InternalLog');
26
+ const mockedInternalLog = (InternalLog as unknown) as {
27
+ log: jest.MockedFunction<typeof InternalLog.log>;
28
+ };
29
+ jest.spyOn(global.Math, 'random');
30
+
31
+ const DdRum = NativeModules.DdRum;
32
+
33
+ function randomInt(max: number): number {
34
+ return Math.floor(Math.random() * max);
77
35
  }
78
36
 
79
37
  const flushPromises = () => new Promise(setImmediate);
@@ -84,344 +42,706 @@ beforeEach(() => {
84
42
 
85
43
  // we need this because with ms precision between Date.now() calls we can get 0, so we advance
86
44
  // it manually with each call
87
- let now = Date.now()
45
+ let now = Date.now();
88
46
  jest.spyOn(Date, 'now').mockImplementation(() => {
89
- now += 5
90
- return now
91
- })
47
+ now += 5;
48
+ return now;
49
+ });
92
50
 
93
51
  jest.setTimeout(20000);
94
- })
52
+ });
95
53
 
96
54
  afterEach(() => {
97
55
  DdRumResourceTracking.stopTracking();
98
- Date.now.mockClear();
99
- })
100
-
101
-
102
- it('M intercept XHR request W startTracking() + XHR.open() + XHR.send()', async () => {
103
- // GIVEN
104
- let method = "GET"
105
- let url = "https://api.example.com/v2/user"
106
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
107
-
108
- // WHEN
109
- const xhr = new XMLHttpRequest();
110
- xhr.open(method, url);
111
- xhr.send();
112
- xhr.notifyResponseArrived();
113
- xhr.complete(200, 'ok');
114
- await flushPromises();
115
-
116
- // THEN
117
- expect(DdRum.startResource.mock.calls.length).toBe(1);
118
- expect(DdRum.startResource.mock.calls[0][1]).toBe(method);
119
- expect(DdRum.startResource.mock.calls[0][2]).toBe(url);
120
-
121
- expect(DdRum.stopResource.mock.calls.length).toBe(1);
122
- expect(DdRum.stopResource.mock.calls[0][0]).toBe(DdRum.startResource.mock.calls[0][0]);
123
- expect(DdRum.stopResource.mock.calls[0][1]).toBe(200);
124
- expect(DdRum.stopResource.mock.calls[0][2]).toBe('xhr');
125
-
126
- expect(xhr.originalOpenCalled).toBe(true);
127
- expect(xhr.originalSendCalled).toBe(true);
128
- expect(xhr.originalOnReadyStateChangeCalled).toBe(true);
129
- })
130
-
131
- it('M intercept failing XHR request W startTracking() + XHR.open() + XHR.send()', async () => {
132
- // GIVEN
133
- let method = "GET"
134
- let url = "https://api.example.com/v2/user"
135
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
136
-
137
- // WHEN
138
- const xhr = new XMLHttpRequest();
139
- xhr.open(method, url);
140
- xhr.send();
141
- xhr.notifyResponseArrived();
142
- xhr.complete(500, 'error');
143
- await flushPromises();
144
-
145
- // THEN
146
- expect(DdRum.startResource.mock.calls.length).toBe(1);
147
- expect(DdRum.startResource.mock.calls[0][1]).toBe(method);
148
- expect(DdRum.startResource.mock.calls[0][2]).toBe(url);
149
-
150
- expect(DdRum.stopResource.mock.calls.length).toBe(1);
151
- expect(DdRum.stopResource.mock.calls[0][0]).toBe(DdRum.startResource.mock.calls[0][0]);
152
- expect(DdRum.stopResource.mock.calls[0][1]).toBe(500);
153
- expect(DdRum.stopResource.mock.calls[0][2]).toBe('xhr');
154
-
155
- expect(xhr.originalOpenCalled).toBe(true);
156
- expect(xhr.originalSendCalled).toBe(true);
157
- expect(xhr.originalOnReadyStateChangeCalled).toBe(true);
158
- })
159
-
160
- it('M intercept aborted XHR request W startTracking() + XHR.open() + XHR.send() + XHR.abort()', async () => {
161
- // GIVEN
162
- let method = "GET"
163
- let url = "https://api.example.com/v2/user"
164
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
165
-
166
- // WHEN
167
- const xhr = new XMLHttpRequest();
168
- xhr.open(method, url);
169
- xhr.send();
170
- xhr.abort();
171
- xhr.complete(0, undefined);
172
- await flushPromises();
173
-
174
- // THEN
175
- expect(DdRum.startResource.mock.calls.length).toBe(1);
176
- expect(DdRum.startResource.mock.calls[0][1]).toBe(method);
177
- expect(DdRum.startResource.mock.calls[0][2]).toBe(url);
178
-
179
- expect(DdRum.stopResource.mock.calls.length).toBe(1);
180
- expect(DdRum.stopResource.mock.calls[0][0]).toBe(DdRum.startResource.mock.calls[0][0]);
181
- expect(DdRum.stopResource.mock.calls[0][1]).toBe(0);
182
- expect(DdRum.stopResource.mock.calls[0][2]).toBe('xhr');
183
-
184
- expect(xhr.originalOpenCalled).toBe(true);
185
- expect(xhr.originalSendCalled).toBe(true);
186
- expect(xhr.originalOnReadyStateChangeCalled).toBe(true);
187
- })
188
-
189
-
190
- it('M add the span id in the request headers W startTracking() + XHR.open() + XHR.send()', async () => {
191
- // GIVEN
192
- let method = "GET"
193
- let url = "https://api.example.com/v2/user"
194
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
195
-
196
- // WHEN
197
- const xhr = new XMLHttpRequest();
198
- xhr.open(method, url);
199
- xhr.send();
200
- xhr.notifyResponseArrived();
201
- xhr.complete(200, 'ok');
202
- await flushPromises();
203
-
204
- // THEN
205
- const spanId = xhr.headers[PARENT_ID_HEADER_KEY];
206
- expect(spanId).toBeDefined();
207
- expect(spanId).toMatch(/[1-9].+/);
208
- })
209
-
210
- it('M add the trace id in the request headers W startTracking() + XHR.open() + XHR.send()', async () => {
211
- // GIVEN
212
- let method = "GET"
213
- let url = "https://api.example.com/v2/user"
214
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
215
-
216
- // WHEN
217
- const xhr = new XMLHttpRequest();
218
- xhr.open(method, url);
219
- xhr.send();
220
- xhr.notifyResponseArrived();
221
- xhr.complete(200, 'ok');
222
- await flushPromises();
223
-
224
- // THEN
225
- const traceId = xhr.headers[TRACE_ID_HEADER_KEY];
226
- expect(traceId).toBeDefined();
227
- expect(traceId).toMatch(/[1-9].+/);
228
- })
229
-
230
- it('M generate different ids for spanId and traceId in request headers', async () => {
231
- // GIVEN
232
- let method = "GET"
233
- let url = "https://api.example.com/v2/user"
234
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
235
-
236
- // WHEN
237
- const xhr = new XMLHttpRequest();
238
- xhr.open(method, url);
239
- xhr.send();
240
- xhr.notifyResponseArrived();
241
- xhr.complete(200, 'ok');
242
- await flushPromises();
243
-
244
- // THEN
245
- const traceId = xhr.headers[TRACE_ID_HEADER_KEY];
246
- const spanId = xhr.headers[PARENT_ID_HEADER_KEY];
247
- expect(traceId !== spanId).toBeTruthy()
248
- })
249
-
250
- it('M add origin as RUM in the request headers W startTracking() + XHR.open() + XHR.send()', async () => {
251
- // GIVEN
252
- let method = "GET"
253
- let url = "https://api.example.com/v2/user"
254
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
255
-
256
- // WHEN
257
- const xhr = new XMLHttpRequest();
258
- xhr.open(method, url);
259
- xhr.send();
260
- xhr.notifyResponseArrived();
261
- xhr.complete(200, 'ok');
262
- await flushPromises();
263
-
264
- // THEN
265
- expect(xhr.headers[ORIGIN_HEADER_KEY]).toBe(ORIGIN_RUM)
266
- })
267
-
268
- it('M add the span id as resource attributes W startTracking() + XHR.open() + XHR.send()', async () => {
269
- // GIVEN
270
- let method = "GET"
271
- let url = "https://api.example.com/v2/user"
272
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
273
-
274
- // WHEN
275
- const xhr = new XMLHttpRequest();
276
- xhr.open(method, url);
277
- xhr.send();
278
- xhr.notifyResponseArrived();
279
- xhr.complete(200, 'ok');
280
- await flushPromises();
281
-
282
- // THEN
283
- const spanId = DdRum.startResource.mock.calls[0][3]["_dd.span_id"];
284
- expect(spanId).toBeDefined();
285
- expect(spanId).toMatch(/[1-9].+/);
286
- })
287
-
288
- it('M add the trace id as resource attributes W startTracking() + XHR.open() + XHR.send()', async () => {
289
- // GIVEN
290
- let method = "GET"
291
- let url = "https://api.example.com/v2/user"
292
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
293
-
294
- // WHEN
295
- const xhr = new XMLHttpRequest();
296
- xhr.open(method, url);
297
- xhr.send();
298
- xhr.notifyResponseArrived();
299
- xhr.complete(200, 'ok');
300
- await flushPromises();
301
-
302
- // THEN
303
- const traceId = DdRum.startResource.mock.calls[0][3]["_dd.trace_id"];
304
- expect(traceId).toBeDefined();
305
- expect(traceId).toMatch(/[1-9].+/);
306
- })
307
-
308
- it('M generate different ids for spanId and traceId for resource attributes', async () => {
309
- // GIVEN
310
- let method = "GET"
311
- let url = "https://api.example.com/v2/user"
312
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
313
-
314
- // WHEN
315
- const xhr = new XMLHttpRequest();
316
- xhr.open(method, url);
317
- xhr.send();
318
- xhr.notifyResponseArrived();
319
- xhr.complete(200, 'ok');
320
- await flushPromises();
321
-
322
- // THEN
323
- const traceId = DdRum.startResource.mock.calls[0][3]["_dd.trace_id"];
324
- const spanId = DdRum.startResource.mock.calls[0][3]["_dd.span_id"];
325
- expect(traceId !== spanId).toBeTruthy();
326
- })
327
-
328
- describe.each([['android'], ['ios']])('timings test', (platform) => {
329
- it(`M generate resource timings W startTracking() + XHR.open() + XHR.send(), platform=${platform}`, async () => {
330
- // GIVEN
331
- let method = "GET"
332
- let url = "https://api.example.com/v2/user"
333
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
334
-
335
- jest.doMock('react-native/Libraries/Utilities/Platform', () => ({
336
- OS: platform
337
- }));
338
-
339
- // WHEN
340
- const xhr = new XMLHttpRequest();
341
- xhr.open(method, url);
342
- xhr.send();
343
- xhr.notifyResponseArrived();
344
- xhr.complete(200, 'ok');
345
- await flushPromises();
346
-
347
- // THEN
348
- const timings = DdRum.stopResource.mock.calls[0][3]["_dd.resource_timings"];
349
-
350
- if (Platform.OS === 'ios') {
351
- expect(timings['firstByte']['startTime']).toBeGreaterThan(0)
352
- } else {
353
- expect(timings['firstByte']['startTime']).toBe(0)
354
- }
355
- expect(timings['firstByte']['duration']).toBeGreaterThan(0)
356
-
357
- expect(timings['download']['startTime']).toBeGreaterThan(0)
358
- expect(timings['download']['duration']).toBeGreaterThan(0)
359
-
360
- if (Platform.OS === 'ios') {
361
- expect(timings['fetch']['startTime']).toBeGreaterThan(0)
362
- } else {
363
- expect(timings['fetch']['startTime']).toBe(0)
364
- }
365
- expect(timings['fetch']['duration']).toBeGreaterThan(0)
366
- })
367
-
368
- it(`M generate resource timings W startTracking() + XHR.open() + XHR.send() + XHR.abort(), platform=${platform}`, async () => {
369
- // GIVEN
370
- let method = "GET"
371
- let url = "https://api.example.com/v2/user"
372
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
373
-
374
- jest.doMock('react-native/Libraries/Utilities/Platform', () => ({
375
- OS: platform
376
- }));
377
-
378
- // WHEN
379
- const xhr = new XMLHttpRequest();
380
- xhr.open(method, url);
381
- xhr.send();
382
- xhr.notifyResponseArrived();
383
- xhr.abort();
384
- xhr.complete(0, undefined);
385
- await flushPromises();
386
-
387
- // THEN
388
- const timings = DdRum.stopResource.mock.calls[0][3]["_dd.resource_timings"];
389
-
390
- if (Platform.OS === 'ios') {
391
- expect(timings['firstByte']['startTime']).toBeGreaterThan(0)
392
- } else {
393
- expect(timings['firstByte']['startTime']).toBe(0)
394
- }
395
- expect(timings['firstByte']['duration']).toBeGreaterThan(0)
396
-
397
- expect(timings['download']['startTime']).toBeGreaterThan(0)
398
- expect(timings['download']['duration']).toBeGreaterThan(0)
56
+ (Date.now as jest.MockedFunction<typeof Date.now>).mockClear();
57
+ jest.spyOn(global.Math, 'random').mockRestore();
58
+ });
399
59
 
400
- if (Platform.OS === 'ios') {
401
- expect(timings['fetch']['startTime']).toBeGreaterThan(0)
402
- } else {
403
- expect(timings['fetch']['startTime']).toBe(0)
60
+ describe('DdRumResourceTracking', () => {
61
+ describe('resource interception', () => {
62
+ it('intercepts XHR request when startTracking() + XHR.open() + XHR.send()', async () => {
63
+ // GIVEN
64
+ const method = 'GET';
65
+ const url = 'https://api.example.com/v2/user';
66
+ DdRumResourceTracking.startTrackingInternal(
67
+ XMLHttpRequestMock,
68
+ 100
69
+ );
70
+
71
+ // WHEN
72
+ const xhr = new XMLHttpRequestMock();
73
+ xhr.open(method, url);
74
+ xhr.send();
75
+ xhr.notifyResponseArrived();
76
+ xhr.complete(200, 'ok');
77
+ await flushPromises();
78
+
79
+ // THEN
80
+ expect(DdRum.startResource.mock.calls.length).toBe(1);
81
+ expect(DdRum.startResource.mock.calls[0][1]).toBe(method);
82
+ expect(DdRum.startResource.mock.calls[0][2]).toBe(url);
83
+
84
+ expect(DdRum.stopResource.mock.calls.length).toBe(1);
85
+ expect(DdRum.stopResource.mock.calls[0][0]).toBe(
86
+ DdRum.startResource.mock.calls[0][0]
87
+ );
88
+ expect(DdRum.stopResource.mock.calls[0][1]).toBe(200);
89
+ expect(DdRum.stopResource.mock.calls[0][2]).toBe('xhr');
90
+ expect(DdRum.stopResource.mock.calls[0][3]).toBeGreaterThan(0);
91
+
92
+ expect(xhr.originalOpenCalled).toBe(true);
93
+ expect(xhr.originalSendCalled).toBe(true);
94
+ expect(xhr.originalOnReadyStateChangeCalled).toBe(true);
95
+ });
96
+
97
+ it('intercepts failing XHR request when startTracking() + XHR.open() + XHR.send()', async () => {
98
+ // GIVEN
99
+ const method = 'GET';
100
+ const url = 'https://api.example.com/v2/user';
101
+ DdRumResourceTracking.startTrackingInternal(
102
+ XMLHttpRequestMock,
103
+ 100
104
+ );
105
+
106
+ // WHEN
107
+ const xhr = new XMLHttpRequestMock();
108
+ xhr.open(method, url);
109
+ xhr.send();
110
+ xhr.notifyResponseArrived();
111
+ xhr.complete(500, 'error');
112
+ await flushPromises();
113
+
114
+ // THEN
115
+ expect(DdRum.startResource.mock.calls.length).toBe(1);
116
+ expect(DdRum.startResource.mock.calls[0][1]).toBe(method);
117
+ expect(DdRum.startResource.mock.calls[0][2]).toBe(url);
118
+
119
+ expect(DdRum.stopResource.mock.calls.length).toBe(1);
120
+ expect(DdRum.stopResource.mock.calls[0][0]).toBe(
121
+ DdRum.startResource.mock.calls[0][0]
122
+ );
123
+ expect(DdRum.stopResource.mock.calls[0][1]).toBe(500);
124
+ expect(DdRum.stopResource.mock.calls[0][2]).toBe('xhr');
125
+ expect(DdRum.stopResource.mock.calls[0][3]).toBeGreaterThan(0);
126
+
127
+ expect(xhr.originalOpenCalled).toBe(true);
128
+ expect(xhr.originalSendCalled).toBe(true);
129
+ expect(xhr.originalOnReadyStateChangeCalled).toBe(true);
130
+ });
131
+
132
+ it('intercepts aborted XHR request when startTracking() + XHR.open() + XHR.send() + XHR.abort()', async () => {
133
+ // GIVEN
134
+ const method = 'GET';
135
+ const url = 'https://api.example.com/v2/user';
136
+ DdRumResourceTracking.startTrackingInternal(
137
+ XMLHttpRequestMock,
138
+ 100
139
+ );
140
+
141
+ // WHEN
142
+ const xhr = new XMLHttpRequestMock();
143
+ xhr.open(method, url);
144
+ xhr.send();
145
+ xhr.abort();
146
+ xhr.complete(0, undefined);
147
+ await flushPromises();
148
+
149
+ // THEN
150
+ expect(DdRum.startResource.mock.calls.length).toBe(1);
151
+ expect(DdRum.startResource.mock.calls[0][1]).toBe(method);
152
+ expect(DdRum.startResource.mock.calls[0][2]).toBe(url);
153
+
154
+ expect(DdRum.stopResource.mock.calls.length).toBe(1);
155
+ expect(DdRum.stopResource.mock.calls[0][0]).toBe(
156
+ DdRum.startResource.mock.calls[0][0]
157
+ );
158
+ expect(DdRum.stopResource.mock.calls[0][1]).toBe(0);
159
+ expect(DdRum.stopResource.mock.calls[0][2]).toBe('xhr');
160
+ expect(DdRum.stopResource.mock.calls[0][3]).toBe(-1);
161
+
162
+ expect(xhr.originalOpenCalled).toBe(true);
163
+ expect(xhr.originalSendCalled).toBe(true);
164
+ expect(xhr.originalOnReadyStateChangeCalled).toBe(true);
165
+ });
166
+ });
167
+
168
+ describe('request headers', () => {
169
+ it('adds the span id in the request headers when startTracking() + XHR.open() + XHR.send()', async () => {
170
+ // GIVEN
171
+ const method = 'GET';
172
+ const url = 'https://api.example.com/v2/user';
173
+ DdRumResourceTracking.startTrackingInternal(
174
+ XMLHttpRequestMock,
175
+ 100
176
+ );
177
+
178
+ // WHEN
179
+ const xhr = new XMLHttpRequestMock();
180
+ xhr.open(method, url);
181
+ xhr.send();
182
+ xhr.notifyResponseArrived();
183
+ xhr.complete(200, 'ok');
184
+ await flushPromises();
185
+
186
+ // THEN
187
+ const spanId = xhr.requestHeaders[PARENT_ID_HEADER_KEY];
188
+ expect(spanId).toBeDefined();
189
+ expect(spanId).toMatch(/[1-9].+/);
190
+ });
191
+
192
+ it('adds the trace id in the request headers when startTracking() + XHR.open() + XHR.send()', async () => {
193
+ // GIVEN
194
+ const method = 'GET';
195
+ const url = 'https://api.example.com/v2/user';
196
+ DdRumResourceTracking.startTrackingInternal(
197
+ XMLHttpRequestMock,
198
+ 100
199
+ );
200
+
201
+ // WHEN
202
+ const xhr = new XMLHttpRequestMock();
203
+ xhr.open(method, url);
204
+ xhr.send();
205
+ xhr.notifyResponseArrived();
206
+ xhr.complete(200, 'ok');
207
+ await flushPromises();
208
+
209
+ // THEN
210
+ const traceId = xhr.requestHeaders[TRACE_ID_HEADER_KEY];
211
+ expect(traceId).toBeDefined();
212
+ expect(traceId).toMatch(/[1-9].+/);
213
+ });
214
+
215
+ it('generates different ids for spanId and traceId in request headers', async () => {
216
+ // GIVEN
217
+ const method = 'GET';
218
+ const url = 'https://api.example.com/v2/user';
219
+ DdRumResourceTracking.startTrackingInternal(
220
+ XMLHttpRequestMock,
221
+ 100
222
+ );
223
+
224
+ // WHEN
225
+ const xhr = new XMLHttpRequestMock();
226
+ xhr.open(method, url);
227
+ xhr.send();
228
+ xhr.notifyResponseArrived();
229
+ xhr.complete(200, 'ok');
230
+ await flushPromises();
231
+
232
+ // THEN
233
+ const traceId = xhr.requestHeaders[TRACE_ID_HEADER_KEY];
234
+ const spanId = xhr.requestHeaders[PARENT_ID_HEADER_KEY];
235
+ expect(traceId !== spanId).toBeTruthy();
236
+ });
237
+
238
+ it('does not generate spanId and traceId in request headers when tracing is disabled', async () => {
239
+ // GIVEN
240
+ const method = 'GET';
241
+ const url = 'https://api.example.com/v2/user';
242
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, 50);
243
+ jest.spyOn(global.Math, 'random').mockReturnValue(0.7);
244
+
245
+ // WHEN
246
+ const xhr = new XMLHttpRequestMock();
247
+ xhr.open(method, url);
248
+ xhr.send();
249
+ xhr.notifyResponseArrived();
250
+ xhr.complete(200, 'ok');
251
+ await flushPromises();
252
+
253
+ // THEN
254
+ expect(xhr.requestHeaders[TRACE_ID_HEADER_KEY]).toBeUndefined();
255
+ expect(xhr.requestHeaders[PARENT_ID_HEADER_KEY]).toBeUndefined();
256
+ });
257
+
258
+ it('adds origin as RUM in the request headers when startTracking() + XHR.open() + XHR.send()', async () => {
259
+ // GIVEN
260
+ const method = 'GET';
261
+ const url = 'https://api.example.com/v2/user';
262
+ DdRumResourceTracking.startTrackingInternal(
263
+ XMLHttpRequestMock,
264
+ 100
265
+ );
266
+
267
+ // WHEN
268
+ const xhr = new XMLHttpRequestMock();
269
+ xhr.open(method, url);
270
+ xhr.send();
271
+ xhr.notifyResponseArrived();
272
+ xhr.complete(200, 'ok');
273
+ await flushPromises();
274
+
275
+ // THEN
276
+ expect(xhr.requestHeaders[ORIGIN_HEADER_KEY]).toBe(ORIGIN_RUM);
277
+ });
278
+
279
+ it('forces the agent to keep the request generated trace when startTracking() + XHR.open() + XHR.send()', async () => {
280
+ // GIVEN
281
+ const method = 'GET';
282
+ const url = 'https://api.example.com/v2/user';
283
+ DdRumResourceTracking.startTrackingInternal(
284
+ XMLHttpRequestMock,
285
+ 100
286
+ );
287
+
288
+ // WHEN
289
+ const xhr = new XMLHttpRequestMock();
290
+ xhr.open(method, url);
291
+ xhr.send();
292
+ xhr.notifyResponseArrived();
293
+ xhr.complete(200, 'ok');
294
+ await flushPromises();
295
+
296
+ // THEN
297
+ expect(xhr.requestHeaders[SAMPLING_PRIORITY_HEADER_KEY]).toBe('1');
298
+ });
299
+
300
+ it('forces the agent to discard the request generated trace when startTracking when the request is not traced', async () => {
301
+ // GIVEN
302
+ const method = 'GET';
303
+ const url = 'https://api.example.com/v2/user';
304
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, 50);
305
+ jest.spyOn(global.Math, 'random').mockReturnValue(0.7);
306
+
307
+ // WHEN
308
+ const xhr = new XMLHttpRequestMock();
309
+ xhr.open(method, url);
310
+ xhr.send();
311
+ xhr.notifyResponseArrived();
312
+ xhr.complete(200, 'ok');
313
+ await flushPromises();
314
+
315
+ // THEN
316
+ expect(xhr.requestHeaders[SAMPLING_PRIORITY_HEADER_KEY]).toBe('0');
317
+ });
318
+ });
319
+
320
+ describe('DdRum.startResource calls', () => {
321
+ it('adds the span id as resource attributes when startTracking() + XHR.open() + XHR.send()', async () => {
322
+ // GIVEN
323
+ const method = 'GET';
324
+ const url = 'https://api.example.com/v2/user';
325
+ DdRumResourceTracking.startTrackingInternal(
326
+ XMLHttpRequestMock,
327
+ 100
328
+ );
329
+
330
+ // WHEN
331
+ const xhr = new XMLHttpRequestMock();
332
+ xhr.open(method, url);
333
+ xhr.send();
334
+ xhr.notifyResponseArrived();
335
+ xhr.complete(200, 'ok');
336
+ await flushPromises();
337
+
338
+ // THEN
339
+ const spanId = DdRum.startResource.mock.calls[0][3]['_dd.span_id'];
340
+ expect(spanId).toBeDefined();
341
+ expect(spanId).toMatch(/[1-9].+/);
342
+ });
343
+
344
+ it('adds the trace id as resource attributes when startTracking() + XHR.open() + XHR.send()', async () => {
345
+ // GIVEN
346
+ const method = 'GET';
347
+ const url = 'https://api.example.com/v2/user';
348
+ DdRumResourceTracking.startTrackingInternal(
349
+ XMLHttpRequestMock,
350
+ 100
351
+ );
352
+
353
+ // WHEN
354
+ const xhr = new XMLHttpRequestMock();
355
+ xhr.open(method, url);
356
+ xhr.send();
357
+ xhr.notifyResponseArrived();
358
+ xhr.complete(200, 'ok');
359
+ await flushPromises();
360
+
361
+ // THEN
362
+ const traceId =
363
+ DdRum.startResource.mock.calls[0][3]['_dd.trace_id'];
364
+ expect(traceId).toBeDefined();
365
+ expect(traceId).toMatch(/[1-9].+/);
366
+ });
367
+
368
+ it('generates different ids for spanId and traceId for resource attributes', async () => {
369
+ // GIVEN
370
+ const method = 'GET';
371
+ const url = 'https://api.example.com/v2/user';
372
+ DdRumResourceTracking.startTrackingInternal(
373
+ XMLHttpRequestMock,
374
+ 100
375
+ );
376
+
377
+ // WHEN
378
+ const xhr = new XMLHttpRequestMock();
379
+ xhr.open(method, url);
380
+ xhr.send();
381
+ xhr.notifyResponseArrived();
382
+ xhr.complete(200, 'ok');
383
+ await flushPromises();
384
+
385
+ // THEN
386
+ const traceId =
387
+ DdRum.startResource.mock.calls[0][3]['_dd.trace_id'];
388
+ const spanId = DdRum.startResource.mock.calls[0][3]['_dd.span_id'];
389
+ expect(traceId !== spanId).toBeTruthy();
390
+ });
391
+
392
+ it('does not generate spanId and traceId when tracing is disabled', async () => {
393
+ // GIVEN
394
+ const method = 'GET';
395
+ const url = 'https://api.example.com/v2/user';
396
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, 50);
397
+ jest.spyOn(global.Math, 'random').mockReturnValue(0.7);
398
+
399
+ // WHEN
400
+ const xhr = new XMLHttpRequestMock();
401
+ xhr.open(method, url);
402
+ xhr.send();
403
+ xhr.notifyResponseArrived();
404
+ xhr.complete(200, 'ok');
405
+ await flushPromises();
406
+
407
+ // THEN
408
+ expect(DdRum.startResource).not.toHaveBeenCalledWith(
409
+ expect.anything(),
410
+ expect.anything(),
411
+ expect.anything(),
412
+ expect.objectContaining({
413
+ '_dd.trace_id': expect.any(String),
414
+ '_dd.span_id': expect.any(String)
415
+ }),
416
+ expect.anything()
417
+ );
418
+ });
419
+ });
420
+
421
+ describe.each([['android'], ['ios']])('timings test', platform => {
422
+ it(`M generate resource timings when startTracking() + XHR.open() + XHR.send(), platform=${platform}`, async () => {
423
+ // GIVEN
424
+ const method = 'GET';
425
+ const url = 'https://api.example.com/v2/user';
426
+ DdRumResourceTracking.startTrackingInternal(
427
+ XMLHttpRequestMock,
428
+ 100
429
+ );
430
+
431
+ jest.doMock('react-native/Libraries/Utilities/Platform', () => ({
432
+ OS: platform
433
+ }));
434
+
435
+ // WHEN
436
+ const xhr = new XMLHttpRequestMock();
437
+ xhr.open(method, url);
438
+ xhr.send();
439
+ xhr.notifyResponseArrived();
440
+ xhr.complete(200, 'ok');
441
+ await flushPromises();
442
+
443
+ // THEN
444
+ const timings =
445
+ DdRum.stopResource.mock.calls[0][4]['_dd.resource_timings'];
446
+
447
+ if (Platform.OS === 'ios') {
448
+ expect(timings['firstByte']['startTime']).toBeGreaterThan(0);
449
+ } else {
450
+ expect(timings['firstByte']['startTime']).toBe(0);
451
+ }
452
+ expect(timings['firstByte']['duration']).toBeGreaterThan(0);
453
+
454
+ expect(timings['download']['startTime']).toBeGreaterThan(0);
455
+ expect(timings['download']['duration']).toBeGreaterThan(0);
456
+
457
+ if (Platform.OS === 'ios') {
458
+ expect(timings['fetch']['startTime']).toBeGreaterThan(0);
459
+ } else {
460
+ expect(timings['fetch']['startTime']).toBe(0);
461
+ }
462
+ expect(timings['fetch']['duration']).toBeGreaterThan(0);
463
+ });
464
+
465
+ it(`M generate resource timings when startTracking() + XHR.open() + XHR.send() + XHR.abort(), platform=${platform}`, async () => {
466
+ // GIVEN
467
+ const method = 'GET';
468
+ const url = 'https://api.example.com/v2/user';
469
+ DdRumResourceTracking.startTrackingInternal(
470
+ XMLHttpRequestMock,
471
+ 100
472
+ );
473
+
474
+ jest.doMock('react-native/Libraries/Utilities/Platform', () => ({
475
+ OS: platform
476
+ }));
477
+
478
+ // WHEN
479
+ const xhr = new XMLHttpRequestMock();
480
+ xhr.open(method, url);
481
+ xhr.send();
482
+ xhr.notifyResponseArrived();
483
+ xhr.abort();
484
+ xhr.complete(0, undefined);
485
+ await flushPromises();
486
+
487
+ // THEN
488
+ const timings =
489
+ DdRum.stopResource.mock.calls[0][4]['_dd.resource_timings'];
490
+
491
+ if (Platform.OS === 'ios') {
492
+ expect(timings['firstByte']['startTime']).toBeGreaterThan(0);
493
+ } else {
494
+ expect(timings['firstByte']['startTime']).toBe(0);
495
+ }
496
+ expect(timings['firstByte']['duration']).toBeGreaterThan(0);
497
+
498
+ expect(timings['download']['startTime']).toBeGreaterThan(0);
499
+ expect(timings['download']['duration']).toBeGreaterThan(0);
500
+
501
+ if (Platform.OS === 'ios') {
502
+ expect(timings['fetch']['startTime']).toBeGreaterThan(0);
503
+ } else {
504
+ expect(timings['fetch']['startTime']).toBe(0);
505
+ }
506
+ expect(timings['fetch']['duration']).toBeGreaterThan(0);
507
+ });
508
+ });
509
+
510
+ describe('DdRum.stopResource calls', () => {
511
+ it('does not generate resource timings when startTracking() + XHR.open() + XHR.send() + XHR.abort() before load started', async () => {
512
+ // GIVEN
513
+ const method = 'GET';
514
+ const url = 'https://api.example.com/v2/user';
515
+ DdRumResourceTracking.startTrackingInternal(
516
+ XMLHttpRequestMock,
517
+ 100
518
+ );
519
+
520
+ // WHEN
521
+ const xhr = new XMLHttpRequestMock();
522
+ xhr.open(method, url);
523
+ xhr.send();
524
+ xhr.abort();
525
+ xhr.complete(0, undefined);
526
+ await flushPromises();
527
+
528
+ // THEN
529
+ const attributes = DdRum.stopResource.mock.calls[0][4];
530
+
531
+ expect(attributes['_dd.resource_timings']).toBeNull();
532
+ });
533
+ });
534
+
535
+ describe.each(
536
+ ([
537
+ 'blob',
538
+ 'arraybuffer',
539
+ 'text',
540
+ '',
541
+ 'json'
542
+ ] as XMLHttpRequestResponseType[]).map(responseType => {
543
+ const xhr = new XMLHttpRequestMock();
544
+ xhr.readyState = XMLHttpRequestMock.DONE;
545
+ xhr.responseType = responseType;
546
+ xhr.response = {};
547
+
548
+ const contentLength = randomInt(1_000_000_000);
549
+ xhr.setResponseHeader('Content-Length', contentLength.toString());
550
+ return {
551
+ xhr,
552
+ responseType: responseType || '_empty_',
553
+ expectedSize: contentLength
554
+ };
555
+ })
556
+ )(
557
+ 'Response size from response header',
558
+ ({ xhr, responseType, expectedSize }) => {
559
+ it(`M calculate response size when calculateResponseSize(), responseType=${responseType}`, () => {
560
+ // WHEN
561
+ const size = calculateResponseSize(
562
+ (xhr as unknown) as XMLHttpRequest
563
+ );
564
+
565
+ // THEN
566
+ expect(size).toEqual(expectedSize);
567
+ });
404
568
  }
405
- expect(timings['fetch']['duration']).toBeGreaterThan(0)
406
- })
407
- })
408
-
409
- it('M not generate resource timings W startTracking() + XHR.open() + XHR.send() + XHR.abort() before load started', async () => {
410
- // GIVEN
411
- let method = "GET"
412
- let url = "https://api.example.com/v2/user"
413
- DdRumResourceTracking.startTrackingInternal(XMLHttpRequest);
414
-
415
- // WHEN
416
- const xhr = new XMLHttpRequest();
417
- xhr.open(method, url);
418
- xhr.send();
419
- xhr.abort();
420
- xhr.complete(0, undefined);
421
- await flushPromises();
422
-
423
- // THEN
424
- const attributes = DdRum.stopResource.mock.calls[0][3];
425
-
426
- expect(attributes['_dd.resource_timings']).toBeNull()
427
- })
569
+ );
570
+
571
+ describe('response size calculation', () => {
572
+ it('calculates response size when calculateResponseSize() { responseType=blob }', () => {
573
+ // GIVEN
574
+ const xhr = new XMLHttpRequestMock();
575
+ xhr.readyState = XMLHttpRequestMock.DONE;
576
+ xhr.responseType = 'blob';
577
+
578
+ const expectedSize = randomInt(1_000_000);
579
+ xhr.response = {
580
+ get size() {
581
+ return expectedSize;
582
+ }
583
+ };
584
+
585
+ // WHEN
586
+ const size = calculateResponseSize(
587
+ (xhr as unknown) as XMLHttpRequest
588
+ );
589
+
590
+ // THEN
591
+ expect(size).toEqual(expectedSize);
592
+ });
593
+
594
+ it('calculates response size when calculateResponseSize() { responseType=arraybuffer }', () => {
595
+ // GIVEN
596
+ const xhr = new XMLHttpRequestMock();
597
+ xhr.readyState = XMLHttpRequestMock.DONE;
598
+ xhr.responseType = 'arraybuffer';
599
+
600
+ const expectedSize = randomInt(100_000);
601
+ xhr.response = new ArrayBuffer(expectedSize);
602
+
603
+ // WHEN
604
+ const size = calculateResponseSize(
605
+ (xhr as unknown) as XMLHttpRequest
606
+ );
607
+
608
+ // THEN
609
+ expect(size).toEqual(expectedSize);
610
+ });
611
+
612
+ it('calculates response size when calculateResponseSize() { responseType=text }', () => {
613
+ // GIVEN
614
+ const xhr = new XMLHttpRequestMock();
615
+ xhr.readyState = XMLHttpRequestMock.DONE;
616
+ xhr.responseType = 'text';
617
+
618
+ // size per char is 24, but in bytes it is 33.
619
+ const expectedSize = 33;
620
+ xhr.response = '{"foo": "bar+úñïçôδè ℓ"}';
621
+
622
+ // WHEN
623
+ const size = calculateResponseSize(
624
+ (xhr as unknown) as XMLHttpRequest
625
+ );
626
+
627
+ // THEN
628
+ expect(size).toEqual(expectedSize);
629
+ });
630
+
631
+ it('calculates response size when calculateResponseSize() { responseType=_empty_ }', () => {
632
+ // GIVEN
633
+ const xhr = new XMLHttpRequestMock();
634
+ xhr.readyState = XMLHttpRequestMock.DONE;
635
+ xhr.responseType = '';
636
+
637
+ // size per char is 24, but in bytes it is 33.
638
+ const expectedSize = 33;
639
+ xhr.response = '{"foo": "bar+úñïçôδè ℓ"}';
640
+
641
+ // WHEN
642
+ const size = calculateResponseSize(
643
+ (xhr as unknown) as XMLHttpRequest
644
+ );
645
+
646
+ // THEN
647
+ expect(size).toEqual(expectedSize);
648
+ });
649
+
650
+ it('calculates response size when calculateResponseSize() { responseType=json }', () => {
651
+ // GIVEN
652
+ const xhr = new XMLHttpRequestMock();
653
+ xhr.readyState = XMLHttpRequestMock.DONE;
654
+ xhr.responseType = 'json';
655
+
656
+ const expectedSize = 24;
657
+ xhr.response = { foo: { bar: 'foobar' } };
658
+
659
+ // WHEN
660
+ const size = calculateResponseSize(
661
+ (xhr as unknown) as XMLHttpRequest
662
+ );
663
+
664
+ // THEN
665
+ expect(size).toEqual(expectedSize);
666
+ });
667
+
668
+ it('does not calculate response size when calculateResponseSize() { responseType=document }', () => {
669
+ // GIVEN
670
+ const xhr = new XMLHttpRequestMock();
671
+ xhr.readyState = XMLHttpRequestMock.DONE;
672
+ // document type is not supported by RN, so there are no classes to handle it
673
+ xhr.responseType = 'document';
674
+ xhr.response = {};
675
+
676
+ // WHEN
677
+ const size = calculateResponseSize(
678
+ (xhr as unknown) as XMLHttpRequest
679
+ );
680
+
681
+ // THEN
682
+ expect(size).toEqual(-1);
683
+ });
684
+
685
+ it('returns 0 when calculateResponseSize() { error is thrown }', () => {
686
+ // GIVEN
687
+ mockedInternalLog.log.mockClear();
688
+
689
+ const xhr = new XMLHttpRequestMock();
690
+ xhr.readyState = XMLHttpRequestMock.DONE;
691
+ xhr.responseType = 'blob';
692
+ const error = new Error();
693
+ xhr.response = {
694
+ get size() {
695
+ throw error;
696
+ }
697
+ };
698
+
699
+ // WHEN
700
+ const size = calculateResponseSize(
701
+ (xhr as unknown) as XMLHttpRequest
702
+ );
703
+
704
+ // THEN
705
+ expect(size).toEqual(-1);
706
+ expect(InternalLog.log).toHaveBeenCalledTimes(1);
707
+ expect(InternalLog.log).toHaveBeenCalledWith(
708
+ `${RESOURCE_SIZE_ERROR_MESSAGE}${error}`,
709
+ SdkVerbosity.ERROR
710
+ );
711
+ });
712
+
713
+ it('returns 0 when calculateResponseSize() { size is not a number }', () => {
714
+ // GIVEN
715
+ const xhr = new XMLHttpRequestMock();
716
+ xhr.readyState = XMLHttpRequestMock.DONE;
717
+ xhr.responseType = 'blob';
718
+
719
+ // we pass empty object, so that .size property is missing, we will get undefined
720
+ xhr.response = {};
721
+
722
+ // WHEN
723
+ const size = calculateResponseSize(
724
+ (xhr as unknown) as XMLHttpRequest
725
+ );
726
+
727
+ // THEN
728
+ expect(size).toEqual(-1);
729
+ });
730
+
731
+ it('returns 0 when calculateResponseSize() { no response }', () => {
732
+ // GIVEN
733
+ const xhr = new XMLHttpRequestMock();
734
+ xhr.readyState = XMLHttpRequestMock.DONE;
735
+ xhr.responseType = 'blob';
736
+ xhr.response = null;
737
+
738
+ // WHEN
739
+ const size = calculateResponseSize(
740
+ (xhr as unknown) as XMLHttpRequest
741
+ );
742
+
743
+ // THEN
744
+ expect(size).toEqual(-1);
745
+ });
746
+ });
747
+ });