@datadog/mobile-react-native 1.0.0-rc4 → 1.0.0-rc7

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