forked from open-telemetry/opentelemetry-js-contrib
/
userInteraction.nozone.test.ts
623 lines (563 loc) · 19.9 KB
/
userInteraction.nozone.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const originalSetTimeout = window.setTimeout;
import { trace } from '@opentelemetry/api';
import { isWrapped } from '@opentelemetry/core';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';
import * as tracing from '@opentelemetry/sdk-trace-base';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { UserInteractionInstrumentation } from '../src';
import {
assertClickSpan,
DummySpanExporter,
fakeInteraction,
getData,
} from './helper.test';
const FILE_URL =
'https://raw.githubusercontent.com/open-telemetry/opentelemetry-js/main/package.json';
describe('UserInteractionInstrumentation', () => {
describe('when zone.js is NOT available', () => {
let userInteractionInstrumentation: UserInteractionInstrumentation;
let sandbox: sinon.SinonSandbox;
let webTracerProvider: WebTracerProvider;
let dummySpanExporter: DummySpanExporter;
let exportSpy: sinon.SinonSpy;
let requests: sinon.SinonFakeXMLHttpRequest[] = [];
beforeEach(() => {
sandbox = sinon.createSandbox();
const fakeXhr = sandbox.useFakeXMLHttpRequest();
fakeXhr.onCreate = function (xhr: sinon.SinonFakeXMLHttpRequest) {
requests.push(xhr);
setTimeout(() => {
requests[requests.length - 1].respond(
200,
{ 'Content-Type': 'application/json' },
'{"foo":"bar"}'
);
});
};
sandbox.useFakeTimers();
userInteractionInstrumentation = new UserInteractionInstrumentation({
enabled: false,
});
sandbox
.stub(userInteractionInstrumentation, 'getZoneWithPrototype')
.callsFake(() => {
return false as any;
});
webTracerProvider = new WebTracerProvider();
dummySpanExporter = new DummySpanExporter();
exportSpy = sandbox.stub(dummySpanExporter, 'export');
webTracerProvider.addSpanProcessor(
new tracing.SimpleSpanProcessor(dummySpanExporter)
);
webTracerProvider.register();
registerInstrumentations({
instrumentations: [
userInteractionInstrumentation,
new XMLHttpRequestInstrumentation(),
],
});
// this is needed as window is treated as context and karma is adding
// context which is then detected as spanContext
(window as { context?: {} }).context = undefined;
});
afterEach(() => {
requests = [];
sandbox.restore();
exportSpy.restore();
trace.disable();
});
it('should not break removeEventListener', () => {
let called = false;
const listener = function () {
called = true;
};
// add same listener three different ways
document.body.addEventListener('bodyEvent', listener);
document.body.addEventListener('bodyEvent2', listener);
document.addEventListener('docEvent', listener);
document.body.dispatchEvent(new Event('bodyEvent'));
assert.strictEqual(called, true);
called = false;
// Remove first callback, second type should still fire
document.body.removeEventListener('bodyEvent', listener);
document.body.dispatchEvent(new Event('bodyEvent'));
assert.strictEqual(called, false);
document.body.dispatchEvent(new Event('bodyEvent2'));
assert.strictEqual(called, true);
called = false;
// Remove doc callback, body 2 should still fire
document.removeEventListener('docEvent', listener);
document.dispatchEvent(new Event('docEvent'));
assert.strictEqual(called, false);
document.body.dispatchEvent(new Event('bodyEvent2'));
assert.strictEqual(called, true);
called = false;
// Finally, remove the last one and nothing should fire
document.body.removeEventListener('bodyEvent2', listener);
document.body.dispatchEvent(new Event('bodyEvent'));
document.body.dispatchEvent(new Event('bodyEvent2'));
document.dispatchEvent(new Event('docEvent'));
assert.strictEqual(called, false);
});
it('should not double-register a listener', () => {
let callCount = 0;
const listener = function () {
callCount++;
};
// addEventListener semantics treat the second call as a no-op
document.body.addEventListener('bodyEvent', listener);
document.body.addEventListener('bodyEvent', listener);
document.body.dispatchEvent(new Event('bodyEvent'));
assert.strictEqual(callCount, 1);
// now ensure remove still works
callCount = 0;
document.body.removeEventListener('bodyEvent', listener);
document.body.dispatchEvent(new Event('bodyEvent'));
assert.strictEqual(callCount, 0);
});
it('should handle once-only callbacks', () => {
let callCount = 0;
const listener = function () {
callCount++;
};
// addEventListener semantics treat the second call as a no-op
document.body.addEventListener('bodyEvent', listener, { once: true });
document.body.addEventListener('bodyEvent', listener); // considered a double-register
document.body.dispatchEvent(new Event('bodyEvent'));
assert.strictEqual(callCount, 1);
// now that it's been dispatched once, it's been removed
document.body.dispatchEvent(new Event('bodyEvent'));
assert.strictEqual(callCount, 1);
// should be able to re-add
document.body.addEventListener('bodyEvent', listener);
document.body.dispatchEvent(new Event('bodyEvent'));
assert.strictEqual(callCount, 2);
document.body.dispatchEvent(new Event('bodyEvent'));
assert.strictEqual(callCount, 3);
});
it('should handle EventListener callbacks', () => {
let callCount = 0;
const listener = {
handleEvent(evt: Event) {
if (evt) {
callCount++;
}
},
};
document.body.addEventListener('EventListenerEvent', listener);
document.body.dispatchEvent(new Event('EventListenerEvent'));
assert.strictEqual(callCount, 1);
callCount = 0;
document.body.removeEventListener('EventListenerEvent', listener);
document.body.dispatchEvent(new Event('EventListenerEvent'));
assert.strictEqual(callCount, 0);
});
it('should handle task without async operation', () => {
fakeInteraction();
assert.equal(exportSpy.args.length, 1, 'should export one span');
const spanClick = exportSpy.args[0][0][0];
assertClickSpan(spanClick);
});
it('should handle timeout', done => {
fakeInteraction(() => {
originalSetTimeout(() => {
const spanClick: tracing.ReadableSpan = exportSpy.args[0][0][0];
assert.equal(exportSpy.args.length, 1, 'should export one span');
assertClickSpan(spanClick);
done();
});
});
sandbox.clock.tick(10);
});
it('should handle target without function getAttribute', done => {
let callback: Function;
const btn: any = {
addEventListener: function (name: string, callbackF: Function) {
callback = callbackF;
},
click: function () {
callback();
},
};
fakeInteraction(() => {
originalSetTimeout(() => {
assert.equal(exportSpy.args.length, 0, 'should NOT export any span');
done();
});
}, btn);
sandbox.clock.tick(10);
});
it('should not create span when element has attribute disabled', done => {
let callback: Function;
const btn: any = {
addEventListener: function (name: string, callbackF: Function) {
callback = callbackF;
},
click: function () {
callback();
},
getAttribute: function () {},
hasAttribute: function (name: string) {
return name === 'disabled' ? true : false;
},
};
fakeInteraction(() => {
originalSetTimeout(() => {
assert.equal(exportSpy.args.length, 0, 'should NOT export any span');
done();
});
}, btn);
sandbox.clock.tick(10);
});
it('should not create span when start span fails', done => {
userInteractionInstrumentation['_tracer'].startSpan = function () {
throw 'foo';
};
fakeInteraction(() => {
originalSetTimeout(() => {
assert.equal(exportSpy.args.length, 0, 'should NOT export any span');
done();
});
});
sandbox.clock.tick(10);
});
it('should handle task with navigation change', done => {
fakeInteraction(() => {
history.pushState(
{ test: 'testing' },
'',
`${location.pathname}#foo=bar1`
);
getData(FILE_URL, () => {
sandbox.clock.tick(1000);
}).then(() => {
originalSetTimeout(() => {
assert.equal(exportSpy.args.length, 2, 'should export 2 spans');
const spanXhr: tracing.ReadableSpan = exportSpy.args[0][0][0];
const spanClick: tracing.ReadableSpan = exportSpy.args[1][0][0];
assert.equal(
spanXhr.parentSpanId,
spanClick.spanContext().spanId,
'xhr span has wrong parent'
);
assert.equal(
spanClick.name,
`Navigation: ${location.pathname}#foo=bar1`
);
const attributes = spanClick.attributes;
assert.equal(attributes.component, 'user-interaction');
assert.equal(attributes.event_type, 'click');
assert.equal(attributes.target_element, 'BUTTON');
assert.equal(attributes.target_xpath, '//*[@id="testBtn"]');
done();
});
});
});
});
it('should handle task with timeout and async operation', done => {
fakeInteraction(() => {
getData(FILE_URL, () => {
sandbox.clock.tick(1000);
}).then(() => {
originalSetTimeout(() => {
assert.equal(exportSpy.args.length, 2, 'should export 2 spans');
const spanXhr: tracing.ReadableSpan = exportSpy.args[0][0][0];
const spanClick: tracing.ReadableSpan = exportSpy.args[1][0][0];
assert.equal(
spanXhr.parentSpanId,
spanClick.spanContext().spanId,
'xhr span has wrong parent'
);
assertClickSpan(spanClick);
const attributes = spanXhr.attributes;
assert.equal(
attributes['http.url'],
'https://raw.githubusercontent.com/open-telemetry/opentelemetry-js/main/package.json'
);
// all other attributes are checked in xhr anyway
done();
});
});
});
});
it('should trace causality of bubbled events', () => {
let callCount = 0;
const listener1 = function () {
callCount++;
};
const listener2 = function () {
callCount++;
};
document.body.addEventListener('click', listener1);
try {
document.body.firstElementChild?.addEventListener('click', listener2);
document.body.firstElementChild?.dispatchEvent(
new MouseEvent('click', { bubbles: true })
);
} finally {
// remove added listener so we don't pollute other tests
document.body.removeEventListener('click', listener1);
}
assert.strictEqual(callCount, 2);
assert.strictEqual(exportSpy.args.length, 2);
assert.strictEqual(
exportSpy.args[0][0][0].traceId,
exportSpy.args[1][0][0].traceId
);
assert.strictEqual(
exportSpy.args[0][0][0].spanId,
exportSpy.args[1][0][0].spanContext().parentSpanId
);
});
it('should handle 3 overlapping interactions', done => {
const btn1 = document.createElement('button');
btn1.setAttribute('id', 'btn1');
const btn2 = document.createElement('button');
btn2.setAttribute('id', 'btn2');
const btn3 = document.createElement('button');
btn3.setAttribute('id', 'btn3');
fakeInteraction(() => {
getData(FILE_URL, () => {
sandbox.clock.tick(10);
}).then(() => {});
}, btn1);
fakeInteraction(() => {
getData(FILE_URL, () => {
sandbox.clock.tick(10);
}).then(() => {});
}, btn2);
fakeInteraction(() => {
getData(FILE_URL, () => {
sandbox.clock.tick(10);
}).then(() => {});
}, btn3);
sandbox.clock.tick(1000);
originalSetTimeout(() => {
assert.equal(exportSpy.args.length, 6, 'should export 6 spans');
const span1: tracing.ReadableSpan = exportSpy.args[0][0][0];
const span2: tracing.ReadableSpan = exportSpy.args[1][0][0];
const span3: tracing.ReadableSpan = exportSpy.args[2][0][0];
const span4: tracing.ReadableSpan = exportSpy.args[3][0][0];
const span5: tracing.ReadableSpan = exportSpy.args[4][0][0];
const span6: tracing.ReadableSpan = exportSpy.args[5][0][0];
assertClickSpan(span1, 'btn1');
assertClickSpan(span2, 'btn2');
assertClickSpan(span3, 'btn3');
assert.strictEqual(
span1.spanContext().spanId,
span4.parentSpanId,
'span4 has wrong parent'
);
assert.strictEqual(
span2.spanContext().spanId,
span5.parentSpanId,
'span5 has wrong parent'
);
assert.strictEqual(
span3.spanContext().spanId,
span6.parentSpanId,
'span6 has wrong parent'
);
done();
});
});
it('should handle interactions listened on document - react < 17', done => {
const btn1 = document.createElement('button');
btn1.setAttribute('id', 'btn1');
document.body.appendChild(btn1);
const btn2 = document.createElement('button');
btn2.setAttribute('id', 'btn2');
document.body.appendChild(btn2);
const listener = (event: MouseEvent) => {
switch (event.target) {
case btn1:
getData(FILE_URL, () => {
sandbox.clock.tick(10);
}).then(() => {});
break;
case btn2:
getData(FILE_URL, () => {
sandbox.clock.tick(10);
}).then(() => {});
break;
}
};
document.addEventListener('click', listener);
try {
btn1.click();
btn2.click();
} finally {
// remove added listener so we don't pollute other tests
document.removeEventListener('click', listener);
}
sandbox.clock.tick(1000);
originalSetTimeout(() => {
assert.equal(exportSpy.args.length, 4, 'should export 4 spans');
const span1: tracing.ReadableSpan = exportSpy.args[0][0][0];
const span2: tracing.ReadableSpan = exportSpy.args[1][0][0];
const span3: tracing.ReadableSpan = exportSpy.args[2][0][0];
const span4: tracing.ReadableSpan = exportSpy.args[3][0][0];
assertClickSpan(span1, 'btn1');
assertClickSpan(span2, 'btn2');
assert.strictEqual(
span1.spanContext().spanId,
span3.parentSpanId,
'span3 has wrong parent'
);
assert.strictEqual(
span2.spanContext().spanId,
span4.parentSpanId,
'span4 has wrong parent'
);
done();
});
});
it('should handle interactions listened on a parent element (bubbled events) - react >= 17', done => {
const root = document.createElement('div');
document.body.appendChild(root);
const btn1 = document.createElement('button');
btn1.setAttribute('id', 'btn1');
root.appendChild(btn1);
const btn2 = document.createElement('button');
btn2.setAttribute('id', 'btn2');
root.appendChild(btn2);
const listenerThis: EventTarget[] = [];
root.addEventListener('click', function (event) {
// Assert here with failure would also affect other tests due to setTimeout bellow
listenerThis.push(this);
switch (event.target) {
case btn1:
getData(FILE_URL, () => {
sandbox.clock.tick(10);
}).then(() => {});
break;
case btn2:
getData(FILE_URL, () => {
sandbox.clock.tick(10);
}).then(() => {});
break;
}
});
btn1.click();
btn2.click();
sandbox.clock.tick(1000);
originalSetTimeout(() => {
assert.strictEqual(
listenerThis[0],
root,
'this inside event listener matches listened target (0)'
);
assert.strictEqual(
listenerThis[1],
root,
'this inside event listener matches listened target (1)'
);
assert.equal(exportSpy.args.length, 4, 'should export 4 spans');
const span1: tracing.ReadableSpan = exportSpy.args[0][0][0];
const span2: tracing.ReadableSpan = exportSpy.args[1][0][0];
const span3: tracing.ReadableSpan = exportSpy.args[2][0][0];
const span4: tracing.ReadableSpan = exportSpy.args[3][0][0];
assertClickSpan(span1, 'btn1');
assertClickSpan(span2, 'btn2');
assert.strictEqual(
span1.spanContext().spanId,
span3.parentSpanId,
'span3 has wrong parent'
);
assert.strictEqual(
span2.spanContext().spanId,
span4.parentSpanId,
'span4 has wrong parent'
);
done();
});
});
it('should handle disable', () => {
assert.strictEqual(
isWrapped(HTMLElement.prototype.addEventListener),
true,
'addEventListener should be wrapped'
);
assert.strictEqual(
isWrapped(HTMLElement.prototype.removeEventListener),
true,
'removeEventListener should be wrapped'
);
assert.strictEqual(
isWrapped(history.replaceState),
true,
'replaceState should be wrapped'
);
assert.strictEqual(
isWrapped(history.pushState),
true,
'pushState should be wrapped'
);
assert.strictEqual(
isWrapped(history.back),
true,
'back should be wrapped'
);
assert.strictEqual(
isWrapped(history.forward),
true,
'forward should be wrapped'
);
assert.strictEqual(isWrapped(history.go), true, 'go should be wrapped');
userInteractionInstrumentation.disable();
assert.strictEqual(
isWrapped(HTMLElement.prototype.addEventListener),
false,
'addEventListener should be unwrapped'
);
assert.strictEqual(
isWrapped(HTMLElement.prototype.removeEventListener),
false,
'removeEventListener should be unwrapped'
);
assert.strictEqual(
isWrapped(history.replaceState),
false,
'replaceState should be unwrapped'
);
assert.strictEqual(
isWrapped(history.pushState),
false,
'pushState should be unwrapped'
);
assert.strictEqual(
isWrapped(history.back),
false,
'back should be unwrapped'
);
assert.strictEqual(
isWrapped(history.forward),
false,
'forward should be unwrapped'
);
assert.strictEqual(
isWrapped(history.go),
false,
'go should be unwrapped'
);
});
});
});