@datadog/mobile-react-native 1.0.0-rc5 → 1.0.0-rc8

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 (128) hide show
  1. package/DatadogSDKReactNative.podspec +1 -1
  2. package/README.md +48 -17
  3. package/android/build.gradle +1 -1
  4. package/android/gradle.properties +4 -4
  5. package/ios/Sources/DdSdk.swift +6 -3
  6. package/lib/commonjs/DdSdkReactNative.js +35 -31
  7. package/lib/commonjs/DdSdkReactNative.js.map +1 -1
  8. package/lib/commonjs/DdSdkReactNativeConfiguration.js +20 -7
  9. package/lib/commonjs/DdSdkReactNativeConfiguration.js.map +1 -1
  10. package/lib/commonjs/InternalLog.js +10 -5
  11. package/lib/commonjs/InternalLog.js.map +1 -1
  12. package/lib/commonjs/ProxyConfiguration.js.map +1 -1
  13. package/lib/commonjs/SdkVerbosity.js.map +1 -1
  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 +19 -54
  20. package/lib/commonjs/foundation.js.map +1 -1
  21. package/lib/commonjs/index.js +27 -19
  22. package/lib/commonjs/index.js.map +1 -1
  23. package/lib/commonjs/rum/instrumentation/DdEventsInterceptor.js +16 -11
  24. package/lib/commonjs/rum/instrumentation/DdEventsInterceptor.js.map +1 -1
  25. package/lib/commonjs/rum/instrumentation/DdRumErrorTracking.js +19 -23
  26. package/lib/commonjs/rum/instrumentation/DdRumErrorTracking.js.map +1 -1
  27. package/lib/commonjs/rum/instrumentation/DdRumResourceTracking.js +118 -42
  28. package/lib/commonjs/rum/instrumentation/DdRumResourceTracking.js.map +1 -1
  29. package/lib/commonjs/rum/instrumentation/DdRumUserInteractionTracking.js +46 -19
  30. package/lib/commonjs/rum/instrumentation/DdRumUserInteractionTracking.js.map +1 -1
  31. package/lib/commonjs/rum/instrumentation/DdRumXhr.js +0 -4
  32. package/lib/commonjs/rum/instrumentation/NoOpEventsInterceptor.js +1 -1
  33. package/lib/commonjs/rum/instrumentation/NoOpEventsInterceptor.js.map +1 -1
  34. package/lib/commonjs/rum/instrumentation/ShallowObjectEqualityChecker.js +34 -0
  35. package/lib/commonjs/rum/instrumentation/ShallowObjectEqualityChecker.js.map +1 -0
  36. package/lib/commonjs/rum/instrumentation/TraceIdentifier.js.map +1 -1
  37. package/lib/commonjs/rum/instrumentation/URLHostParser.js +33 -0
  38. package/lib/commonjs/rum/instrumentation/URLHostParser.js.map +1 -0
  39. package/lib/commonjs/types.js.map +1 -1
  40. package/lib/commonjs/version.js +1 -1
  41. package/lib/commonjs/version.js.map +1 -1
  42. package/lib/module/DdSdkReactNative.js +33 -29
  43. package/lib/module/DdSdkReactNative.js.map +1 -1
  44. package/lib/module/DdSdkReactNativeConfiguration.js +21 -8
  45. package/lib/module/DdSdkReactNativeConfiguration.js.map +1 -1
  46. package/lib/module/InternalLog.js +11 -5
  47. package/lib/module/InternalLog.js.map +1 -1
  48. package/lib/module/ProxyConfiguration.js.map +1 -1
  49. package/lib/module/SdkVerbosity.js.map +1 -1
  50. package/lib/module/TimeProvider.js +63 -0
  51. package/lib/module/TimeProvider.js.map +1 -0
  52. package/lib/module/Timer.js +14 -23
  53. package/lib/module/Timer.js.map +1 -1
  54. package/lib/module/TrackingConsent.js.map +1 -1
  55. package/lib/module/foundation.js +16 -39
  56. package/lib/module/foundation.js.map +1 -1
  57. package/lib/module/index.js +4 -3
  58. package/lib/module/index.js.map +1 -1
  59. package/lib/module/rum/instrumentation/DdEventsInterceptor.js +12 -10
  60. package/lib/module/rum/instrumentation/DdEventsInterceptor.js.map +1 -1
  61. package/lib/module/rum/instrumentation/DdRumErrorTracking.js +19 -23
  62. package/lib/module/rum/instrumentation/DdRumErrorTracking.js.map +1 -1
  63. package/lib/module/rum/instrumentation/DdRumResourceTracking.js +113 -39
  64. package/lib/module/rum/instrumentation/DdRumResourceTracking.js.map +1 -1
  65. package/lib/module/rum/instrumentation/DdRumUserInteractionTracking.js +44 -17
  66. package/lib/module/rum/instrumentation/DdRumUserInteractionTracking.js.map +1 -1
  67. package/lib/module/rum/instrumentation/DdRumXhr.js +1 -1
  68. package/lib/module/rum/instrumentation/NoOpEventsInterceptor.js +1 -1
  69. package/lib/module/rum/instrumentation/NoOpEventsInterceptor.js.map +1 -1
  70. package/lib/module/rum/instrumentation/ShallowObjectEqualityChecker.js +25 -0
  71. package/lib/module/rum/instrumentation/ShallowObjectEqualityChecker.js.map +1 -0
  72. package/lib/module/rum/instrumentation/TraceIdentifier.js.map +1 -1
  73. package/lib/module/rum/instrumentation/URLHostParser.js +24 -0
  74. package/lib/module/rum/instrumentation/URLHostParser.js.map +1 -0
  75. package/lib/module/types.js.map +1 -1
  76. package/lib/module/version.js +1 -1
  77. package/lib/module/version.js.map +1 -1
  78. package/lib/typescript/DdSdkReactNative.d.ts +6 -6
  79. package/lib/typescript/DdSdkReactNativeConfiguration.d.ts +15 -3
  80. package/lib/typescript/InternalLog.d.ts +5 -0
  81. package/lib/typescript/TimeProvider.d.ts +20 -0
  82. package/lib/typescript/Timer.d.ts +3 -2
  83. package/lib/typescript/index.d.ts +4 -3
  84. package/lib/typescript/rum/instrumentation/DdEventsInterceptor.d.ts +1 -0
  85. package/lib/typescript/rum/instrumentation/DdRumErrorTracking.d.ts +2 -2
  86. package/lib/typescript/rum/instrumentation/DdRumResourceTracking.d.ts +19 -9
  87. package/lib/typescript/rum/instrumentation/DdRumUserInteractionTracking.d.ts +3 -3
  88. package/lib/typescript/rum/instrumentation/DdRumXhr.d.ts +13 -3
  89. package/lib/typescript/rum/instrumentation/ShallowObjectEqualityChecker.d.ts +4 -0
  90. package/lib/typescript/rum/instrumentation/URLHostParser.d.ts +6 -0
  91. package/lib/typescript/version.d.ts +1 -1
  92. package/package.json +6 -3
  93. package/src/DdSdkReactNative.tsx +116 -70
  94. package/src/DdSdkReactNativeConfiguration.tsx +22 -13
  95. package/src/InternalLog.tsx +18 -16
  96. package/src/ProxyConfiguration.tsx +5 -5
  97. package/src/SdkVerbosity.tsx +4 -4
  98. package/src/TimeProvider.tsx +64 -0
  99. package/src/Timer.ts +20 -35
  100. package/src/TrackingConsent.tsx +3 -3
  101. package/src/__mocks__/InternalLog.tsx +9 -0
  102. package/src/__tests__/DdRumWrapper.test.tsx +40 -33
  103. package/src/__tests__/DdSdkReactNative.test.tsx +712 -513
  104. package/src/__tests__/InternalLog.test.tsx +114 -117
  105. package/src/__tests__/TimeProvider.test.tsx +75 -0
  106. package/src/__tests__/Timer.test.ts +148 -57
  107. package/src/__tests__/rum/instrumentation/DdEventsInterceptor.test.tsx +151 -92
  108. package/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx +168 -116
  109. package/src/__tests__/rum/instrumentation/DdRumResourceTracking.test.tsx +789 -644
  110. package/src/__tests__/rum/instrumentation/DdRumUserInteractionTracking.test.tsx +239 -85
  111. package/src/__tests__/rum/instrumentation/ShallowObjectEqualityChecker.test.ts +31 -0
  112. package/src/__tests__/rum/instrumentation/TraceIdentifier.test.tsx +13 -15
  113. package/src/__tests__/rum/instrumentation/URLHostParser.test.ts +40 -0
  114. package/src/__tests__/rum/instrumentation/__utils__/XMLHttpRequestMock.ts +97 -0
  115. package/src/foundation.tsx +13 -10
  116. package/src/index.tsx +15 -4
  117. package/src/rum/instrumentation/DdEventsInterceptor.tsx +51 -35
  118. package/src/rum/instrumentation/DdRumErrorTracking.tsx +49 -44
  119. package/src/rum/instrumentation/DdRumResourceTracking.tsx +369 -234
  120. package/src/rum/instrumentation/DdRumUserInteractionTracking.tsx +72 -29
  121. package/src/rum/instrumentation/DdRumXhr.tsx +21 -11
  122. package/src/rum/instrumentation/EventsInterceptor.tsx +3 -3
  123. package/src/rum/instrumentation/NoOpEventsInterceptor.tsx +2 -2
  124. package/src/rum/instrumentation/ShallowObjectEqualityChecker.ts +24 -0
  125. package/src/rum/instrumentation/TraceIdentifier.tsx +19 -19
  126. package/src/rum/instrumentation/URLHostParser.ts +23 -0
  127. package/src/types.tsx +199 -158
  128. package/src/version.ts +1 -1
@@ -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,781 @@ 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(XMLHttpRequestMock, {
67
+ tracingSamplingRate: 100,
68
+ firstPartyHosts: []
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(XMLHttpRequestMock, {
102
+ tracingSamplingRate: 100,
103
+ firstPartyHosts: []
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(XMLHttpRequestMock, {
137
+ tracingSamplingRate: 100,
138
+ firstPartyHosts: []
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(XMLHttpRequestMock, {
174
+ tracingSamplingRate: 100,
175
+ firstPartyHosts: ['api.example.com']
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(XMLHttpRequestMock, {
197
+ tracingSamplingRate: 100,
198
+ firstPartyHosts: ['api.example.com']
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:443/v2/user';
219
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
220
+ tracingSamplingRate: 100,
221
+ firstPartyHosts: ['something.fr', 'example.com']
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 no first party hosts are provided', async () => {
239
+ // GIVEN
240
+ const method = 'GET';
241
+ const url = 'https://api.example.com/v2/user';
242
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
243
+ tracingSamplingRate: 100,
244
+ firstPartyHosts: []
245
+ });
246
+
247
+ // WHEN
248
+ const xhr = new XMLHttpRequestMock();
249
+ xhr.open(method, url);
250
+ xhr.send();
251
+ xhr.notifyResponseArrived();
252
+ xhr.complete(200, 'ok');
253
+ await flushPromises();
254
+
255
+ // THEN
256
+ expect(xhr.requestHeaders[TRACE_ID_HEADER_KEY]).toBeUndefined();
257
+ expect(xhr.requestHeaders[PARENT_ID_HEADER_KEY]).toBeUndefined();
258
+ });
259
+
260
+ it('does not generate spanId and traceId in request headers when no the url does not match first party hosts', async () => {
261
+ // GIVEN
262
+ const method = 'GET';
263
+ const url = 'https://api.example.com/v2/user';
264
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
265
+ tracingSamplingRate: 100,
266
+ firstPartyHosts: ['google.com', 'api.example.co']
267
+ });
268
+
269
+ // WHEN
270
+ const xhr = new XMLHttpRequestMock();
271
+ xhr.open(method, url);
272
+ xhr.send();
273
+ xhr.notifyResponseArrived();
274
+ xhr.complete(200, 'ok');
275
+ await flushPromises();
276
+
277
+ // THEN
278
+ expect(xhr.requestHeaders[TRACE_ID_HEADER_KEY]).toBeUndefined();
279
+ expect(xhr.requestHeaders[PARENT_ID_HEADER_KEY]).toBeUndefined();
280
+ });
281
+
282
+ it('does not crash when provided URL is not a valid one', async () => {
283
+ // GIVEN
284
+ const method = 'GET';
285
+ const url = 'crash';
286
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
287
+ tracingSamplingRate: 100,
288
+ firstPartyHosts: ['example.com']
289
+ });
290
+
291
+ // WHEN
292
+ const xhr = new XMLHttpRequestMock();
293
+ xhr.open(method, url);
294
+ xhr.send();
295
+ xhr.notifyResponseArrived();
296
+ xhr.complete(200, 'ok');
297
+ await flushPromises();
298
+
299
+ // THEN
300
+ expect(xhr.requestHeaders[TRACE_ID_HEADER_KEY]).toBeUndefined();
301
+ expect(xhr.requestHeaders[PARENT_ID_HEADER_KEY]).toBeUndefined();
302
+ });
303
+
304
+ it('does not generate spanId and traceId in request headers when tracing is disabled', async () => {
305
+ // GIVEN
306
+ const method = 'GET';
307
+ const url = 'https://api.example.com/v2/user';
308
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
309
+ tracingSamplingRate: 50,
310
+ firstPartyHosts: ['api.example.com']
311
+ });
312
+ jest.spyOn(global.Math, 'random').mockReturnValue(0.7);
313
+
314
+ // WHEN
315
+ const xhr = new XMLHttpRequestMock();
316
+ xhr.open(method, url);
317
+ xhr.send();
318
+ xhr.notifyResponseArrived();
319
+ xhr.complete(200, 'ok');
320
+ await flushPromises();
321
+
322
+ // THEN
323
+ expect(xhr.requestHeaders[TRACE_ID_HEADER_KEY]).toBeUndefined();
324
+ expect(xhr.requestHeaders[PARENT_ID_HEADER_KEY]).toBeUndefined();
325
+ });
326
+
327
+ it('adds origin as RUM in the request headers when startTracking() + XHR.open() + XHR.send()', async () => {
328
+ // GIVEN
329
+ const method = 'GET';
330
+ const url = 'https://api.example.com/v2/user';
331
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
332
+ tracingSamplingRate: 100,
333
+ firstPartyHosts: []
334
+ });
335
+
336
+ // WHEN
337
+ const xhr = new XMLHttpRequestMock();
338
+ xhr.open(method, url);
339
+ xhr.send();
340
+ xhr.notifyResponseArrived();
341
+ xhr.complete(200, 'ok');
342
+ await flushPromises();
343
+
344
+ // THEN
345
+ expect(xhr.requestHeaders[ORIGIN_HEADER_KEY]).toBe(ORIGIN_RUM);
346
+ });
347
+
348
+ it('forces the agent to keep the request generated trace when startTracking() + XHR.open() + XHR.send()', async () => {
349
+ // GIVEN
350
+ const method = 'GET';
351
+ const url = 'https://api.example.com/v2/user';
352
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
353
+ tracingSamplingRate: 100,
354
+ firstPartyHosts: ['api.example.com']
355
+ });
356
+
357
+ // WHEN
358
+ const xhr = new XMLHttpRequestMock();
359
+ xhr.open(method, url);
360
+ xhr.send();
361
+ xhr.notifyResponseArrived();
362
+ xhr.complete(200, 'ok');
363
+ await flushPromises();
364
+
365
+ // THEN
366
+ expect(xhr.requestHeaders[SAMPLING_PRIORITY_HEADER_KEY]).toBe('1');
367
+ });
368
+
369
+ it('forces the agent to discard the request generated trace when startTracking when the request is not traced', async () => {
370
+ // GIVEN
371
+ const method = 'GET';
372
+ const url = 'https://api.example.com/v2/user';
373
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
374
+ tracingSamplingRate: 50,
375
+ firstPartyHosts: ['api.example.com']
376
+ });
377
+ jest.spyOn(global.Math, 'random').mockReturnValue(0.7);
378
+
379
+ // WHEN
380
+ const xhr = new XMLHttpRequestMock();
381
+ xhr.open(method, url);
382
+ xhr.send();
383
+ xhr.notifyResponseArrived();
384
+ xhr.complete(200, 'ok');
385
+ await flushPromises();
386
+
387
+ // THEN
388
+ expect(xhr.requestHeaders[SAMPLING_PRIORITY_HEADER_KEY]).toBe('0');
389
+ });
390
+ });
391
+
392
+ describe('DdRum.startResource calls', () => {
393
+ it('adds the span id as resource attributes when startTracking() + XHR.open() + XHR.send()', async () => {
394
+ // GIVEN
395
+ const method = 'GET';
396
+ const url = 'https://api.example.com/v2/user';
397
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
398
+ tracingSamplingRate: 100,
399
+ firstPartyHosts: ['api.example.com']
400
+ });
401
+
402
+ // WHEN
403
+ const xhr = new XMLHttpRequestMock();
404
+ xhr.open(method, url);
405
+ xhr.send();
406
+ xhr.notifyResponseArrived();
407
+ xhr.complete(200, 'ok');
408
+ await flushPromises();
409
+
410
+ // THEN
411
+ const spanId = DdRum.startResource.mock.calls[0][3]['_dd.span_id'];
412
+ expect(spanId).toBeDefined();
413
+ expect(spanId).toMatch(/[1-9].+/);
414
+ });
415
+
416
+ it('adds the trace id as resource attributes when startTracking() + XHR.open() + XHR.send()', async () => {
417
+ // GIVEN
418
+ const method = 'GET';
419
+ const url = 'https://api.example.com/v2/user';
420
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
421
+ tracingSamplingRate: 100,
422
+ firstPartyHosts: ['api.example.com']
423
+ });
424
+
425
+ // WHEN
426
+ const xhr = new XMLHttpRequestMock();
427
+ xhr.open(method, url);
428
+ xhr.send();
429
+ xhr.notifyResponseArrived();
430
+ xhr.complete(200, 'ok');
431
+ await flushPromises();
432
+
433
+ // THEN
434
+ const traceId =
435
+ DdRum.startResource.mock.calls[0][3]['_dd.trace_id'];
436
+ expect(traceId).toBeDefined();
437
+ expect(traceId).toMatch(/[1-9].+/);
438
+ });
439
+
440
+ it('generates different ids for spanId and traceId for resource attributes', async () => {
441
+ // GIVEN
442
+ const method = 'GET';
443
+ const url = 'https://api.example.com/v2/user';
444
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
445
+ tracingSamplingRate: 100,
446
+ firstPartyHosts: ['api.example.com']
447
+ });
448
+
449
+ // WHEN
450
+ const xhr = new XMLHttpRequestMock();
451
+ xhr.open(method, url);
452
+ xhr.send();
453
+ xhr.notifyResponseArrived();
454
+ xhr.complete(200, 'ok');
455
+ await flushPromises();
456
+
457
+ // THEN
458
+ const traceId =
459
+ DdRum.startResource.mock.calls[0][3]['_dd.trace_id'];
460
+ const spanId = DdRum.startResource.mock.calls[0][3]['_dd.span_id'];
461
+ expect(traceId !== spanId).toBeTruthy();
462
+ });
463
+
464
+ it('does not generate spanId and traceId when tracing is disabled', async () => {
465
+ // GIVEN
466
+ const method = 'GET';
467
+ const url = 'https://api.example.com/v2/user';
468
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
469
+ tracingSamplingRate: 50,
470
+ firstPartyHosts: ['api.example.com']
471
+ });
472
+ jest.spyOn(global.Math, 'random').mockReturnValue(0.7);
473
+
474
+ // WHEN
475
+ const xhr = new XMLHttpRequestMock();
476
+ xhr.open(method, url);
477
+ xhr.send();
478
+ xhr.notifyResponseArrived();
479
+ xhr.complete(200, 'ok');
480
+ await flushPromises();
481
+
482
+ // THEN
483
+ expect(DdRum.startResource).not.toHaveBeenCalledWith(
484
+ expect.anything(),
485
+ expect.anything(),
486
+ expect.anything(),
487
+ expect.objectContaining({
488
+ '_dd.trace_id': expect.any(String),
489
+ '_dd.span_id': expect.any(String)
490
+ }),
491
+ expect.anything()
492
+ );
493
+ });
494
+ });
495
+
496
+ describe.each([['android'], ['ios']])('timings test', platform => {
497
+ it(`M generate resource timings when startTracking() + XHR.open() + XHR.send(), platform=${platform}`, async () => {
498
+ // GIVEN
499
+ const method = 'GET';
500
+ const url = 'https://api.example.com/v2/user';
501
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
502
+ tracingSamplingRate: 100,
503
+ firstPartyHosts: []
504
+ });
505
+
506
+ jest.doMock('react-native/Libraries/Utilities/Platform', () => ({
507
+ OS: platform
508
+ }));
509
+
510
+ // WHEN
511
+ const xhr = new XMLHttpRequestMock();
512
+ xhr.open(method, url);
513
+ xhr.send();
514
+ xhr.notifyResponseArrived();
515
+ xhr.complete(200, 'ok');
516
+ await flushPromises();
517
+
518
+ // THEN
519
+ const timings =
520
+ DdRum.stopResource.mock.calls[0][4]['_dd.resource_timings'];
521
+
522
+ if (Platform.OS === 'ios') {
523
+ expect(timings['firstByte']['startTime']).toBeGreaterThan(0);
524
+ } else {
525
+ expect(timings['firstByte']['startTime']).toBe(0);
526
+ }
527
+ expect(timings['firstByte']['duration']).toBeGreaterThan(0);
528
+
529
+ expect(timings['download']['startTime']).toBeGreaterThan(0);
530
+ expect(timings['download']['duration']).toBeGreaterThan(0);
531
+
532
+ if (Platform.OS === 'ios') {
533
+ expect(timings['fetch']['startTime']).toBeGreaterThan(0);
534
+ } else {
535
+ expect(timings['fetch']['startTime']).toBe(0);
536
+ }
537
+ expect(timings['fetch']['duration']).toBeGreaterThan(0);
538
+ });
539
+
540
+ it(`M generate resource timings when startTracking() + XHR.open() + XHR.send() + XHR.abort(), platform=${platform}`, async () => {
541
+ // GIVEN
542
+ const method = 'GET';
543
+ const url = 'https://api.example.com/v2/user';
544
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
545
+ tracingSamplingRate: 100,
546
+ firstPartyHosts: []
547
+ });
548
+
549
+ jest.doMock('react-native/Libraries/Utilities/Platform', () => ({
550
+ OS: platform
551
+ }));
552
+
553
+ // WHEN
554
+ const xhr = new XMLHttpRequestMock();
555
+ xhr.open(method, url);
556
+ xhr.send();
557
+ xhr.notifyResponseArrived();
558
+ xhr.abort();
559
+ xhr.complete(0, undefined);
560
+ await flushPromises();
561
+
562
+ // THEN
563
+ const timings =
564
+ DdRum.stopResource.mock.calls[0][4]['_dd.resource_timings'];
565
+
566
+ if (Platform.OS === 'ios') {
567
+ expect(timings['firstByte']['startTime']).toBeGreaterThan(0);
568
+ } else {
569
+ expect(timings['firstByte']['startTime']).toBe(0);
570
+ }
571
+ expect(timings['firstByte']['duration']).toBeGreaterThan(0);
572
+
573
+ expect(timings['download']['startTime']).toBeGreaterThan(0);
574
+ expect(timings['download']['duration']).toBeGreaterThan(0);
575
+
576
+ if (Platform.OS === 'ios') {
577
+ expect(timings['fetch']['startTime']).toBeGreaterThan(0);
578
+ } else {
579
+ expect(timings['fetch']['startTime']).toBe(0);
580
+ }
581
+ expect(timings['fetch']['duration']).toBeGreaterThan(0);
582
+ });
583
+ });
584
+
585
+ describe('DdRum.stopResource calls', () => {
586
+ it('does not generate resource timings when startTracking() + XHR.open() + XHR.send() + XHR.abort() before load started', async () => {
587
+ // GIVEN
588
+ const method = 'GET';
589
+ const url = 'https://api.example.com/v2/user';
590
+ DdRumResourceTracking.startTrackingInternal(XMLHttpRequestMock, {
591
+ tracingSamplingRate: 100,
592
+ firstPartyHosts: []
593
+ });
594
+
595
+ // WHEN
596
+ const xhr = new XMLHttpRequestMock();
597
+ xhr.open(method, url);
598
+ xhr.send();
599
+ xhr.abort();
600
+ xhr.complete(0, undefined);
601
+ await flushPromises();
602
+
603
+ // THEN
604
+ const attributes = DdRum.stopResource.mock.calls[0][4];
605
+
606
+ expect(attributes['_dd.resource_timings']).toBeNull();
607
+ });
608
+ });
609
+
610
+ describe.each(
611
+ ([
612
+ 'blob',
613
+ 'arraybuffer',
614
+ 'text',
615
+ '',
616
+ 'json'
617
+ ] as XMLHttpRequestResponseType[]).map(responseType => {
618
+ const xhr = new XMLHttpRequestMock();
619
+ xhr.readyState = XMLHttpRequestMock.DONE;
620
+ xhr.responseType = responseType;
621
+ xhr.response = {};
622
+
623
+ const contentLength = randomInt(1_000_000_000);
624
+ xhr.setResponseHeader('Content-Length', contentLength.toString());
625
+ return {
626
+ xhr,
627
+ responseType: responseType || '_empty_',
628
+ expectedSize: contentLength
629
+ };
630
+ })
631
+ )(
632
+ 'Response size from response header',
633
+ ({ xhr, responseType, expectedSize }) => {
634
+ it(`M calculate response size when calculateResponseSize(), responseType=${responseType}`, () => {
635
+ // WHEN
636
+ const size = calculateResponseSize(
637
+ (xhr as unknown) as XMLHttpRequest
638
+ );
639
+
640
+ // THEN
641
+ expect(size).toEqual(expectedSize);
642
+ });
469
643
  }
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
- })
644
+ );
645
+
646
+ describe('response size calculation', () => {
647
+ it('calculates response size when calculateResponseSize() { responseType=blob }', () => {
648
+ // GIVEN
649
+ const xhr = new XMLHttpRequestMock();
650
+ xhr.readyState = XMLHttpRequestMock.DONE;
651
+ xhr.responseType = 'blob';
652
+
653
+ const expectedSize = randomInt(1_000_000);
654
+ xhr.response = {
655
+ get size() {
656
+ return expectedSize;
657
+ }
658
+ };
659
+
660
+ // WHEN
661
+ const size = calculateResponseSize(
662
+ (xhr as unknown) as XMLHttpRequest
663
+ );
664
+
665
+ // THEN
666
+ expect(size).toEqual(expectedSize);
667
+ });
668
+
669
+ it('calculates response size when calculateResponseSize() { responseType=arraybuffer }', () => {
670
+ // GIVEN
671
+ const xhr = new XMLHttpRequestMock();
672
+ xhr.readyState = XMLHttpRequestMock.DONE;
673
+ xhr.responseType = 'arraybuffer';
674
+
675
+ const expectedSize = randomInt(100_000);
676
+ xhr.response = new ArrayBuffer(expectedSize);
677
+
678
+ // WHEN
679
+ const size = calculateResponseSize(
680
+ (xhr as unknown) as XMLHttpRequest
681
+ );
682
+
683
+ // THEN
684
+ expect(size).toEqual(expectedSize);
685
+ });
686
+
687
+ it('calculates response size when calculateResponseSize() { responseType=text }', () => {
688
+ // GIVEN
689
+ const xhr = new XMLHttpRequestMock();
690
+ xhr.readyState = XMLHttpRequestMock.DONE;
691
+ xhr.responseType = 'text';
692
+
693
+ // size per char is 24, but in bytes it is 33.
694
+ const expectedSize = 33;
695
+ xhr.response = '{"foo": "bar+úñïçôδè ℓ"}';
696
+
697
+ // WHEN
698
+ const size = calculateResponseSize(
699
+ (xhr as unknown) as XMLHttpRequest
700
+ );
701
+
702
+ // THEN
703
+ expect(size).toEqual(expectedSize);
704
+ });
705
+
706
+ it('calculates response size when calculateResponseSize() { responseType=_empty_ }', () => {
707
+ // GIVEN
708
+ const xhr = new XMLHttpRequestMock();
709
+ xhr.readyState = XMLHttpRequestMock.DONE;
710
+ xhr.responseType = '';
711
+
712
+ // size per char is 24, but in bytes it is 33.
713
+ const expectedSize = 33;
714
+ xhr.response = '{"foo": "bar+úñïçôδè ℓ"}';
715
+
716
+ // WHEN
717
+ const size = calculateResponseSize(
718
+ (xhr as unknown) as XMLHttpRequest
719
+ );
720
+
721
+ // THEN
722
+ expect(size).toEqual(expectedSize);
723
+ });
724
+
725
+ it('calculates response size when calculateResponseSize() { responseType=json }', () => {
726
+ // GIVEN
727
+ const xhr = new XMLHttpRequestMock();
728
+ xhr.readyState = XMLHttpRequestMock.DONE;
729
+ xhr.responseType = 'json';
730
+
731
+ const expectedSize = 24;
732
+ xhr.response = { foo: { bar: 'foobar' } };
733
+
734
+ // WHEN
735
+ const size = calculateResponseSize(
736
+ (xhr as unknown) as XMLHttpRequest
737
+ );
738
+
739
+ // THEN
740
+ expect(size).toEqual(expectedSize);
741
+ });
742
+
743
+ it('does not calculate response size when calculateResponseSize() { responseType=document }', () => {
744
+ // GIVEN
745
+ const xhr = new XMLHttpRequestMock();
746
+ xhr.readyState = XMLHttpRequestMock.DONE;
747
+ // document type is not supported by RN, so there are no classes to handle it
748
+ xhr.responseType = 'document';
749
+ xhr.response = {};
750
+
751
+ // WHEN
752
+ const size = calculateResponseSize(
753
+ (xhr as unknown) as XMLHttpRequest
754
+ );
755
+
756
+ // THEN
757
+ expect(size).toEqual(-1);
758
+ });
759
+
760
+ it('returns 0 when calculateResponseSize() { error is thrown }', () => {
761
+ // GIVEN
762
+ mockedInternalLog.log.mockClear();
763
+
764
+ const xhr = new XMLHttpRequestMock();
765
+ xhr.readyState = XMLHttpRequestMock.DONE;
766
+ xhr.responseType = 'blob';
767
+ const error = new Error();
768
+ xhr.response = {
769
+ get size() {
770
+ throw error;
771
+ }
772
+ };
773
+
774
+ // WHEN
775
+ const size = calculateResponseSize(
776
+ (xhr as unknown) as XMLHttpRequest
777
+ );
778
+
779
+ // THEN
780
+ expect(size).toEqual(-1);
781
+ expect(InternalLog.log).toHaveBeenCalledTimes(1);
782
+ expect(InternalLog.log).toHaveBeenCalledWith(
783
+ `${RESOURCE_SIZE_ERROR_MESSAGE}${error}`,
784
+ SdkVerbosity.ERROR
785
+ );
786
+ });
787
+
788
+ it('returns 0 when calculateResponseSize() { size is not a number }', () => {
789
+ // GIVEN
790
+ const xhr = new XMLHttpRequestMock();
791
+ xhr.readyState = XMLHttpRequestMock.DONE;
792
+ xhr.responseType = 'blob';
793
+
794
+ // we pass empty object, so that .size property is missing, we will get undefined
795
+ xhr.response = {};
796
+
797
+ // WHEN
798
+ const size = calculateResponseSize(
799
+ (xhr as unknown) as XMLHttpRequest
800
+ );
801
+
802
+ // THEN
803
+ expect(size).toEqual(-1);
804
+ });
805
+
806
+ it('returns 0 when calculateResponseSize() { no response }', () => {
807
+ // GIVEN
808
+ const xhr = new XMLHttpRequestMock();
809
+ xhr.readyState = XMLHttpRequestMock.DONE;
810
+ xhr.responseType = 'blob';
811
+ xhr.response = null;
812
+
813
+ // WHEN
814
+ const size = calculateResponseSize(
815
+ (xhr as unknown) as XMLHttpRequest
816
+ );
817
+
818
+ // THEN
819
+ expect(size).toEqual(-1);
820
+ });
821
+ });
822
+ });