forked from facebook/react
/
ReactDOMEventListener-test.js
742 lines (678 loc) · 22.7 KB
/
ReactDOMEventListener-test.js
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
describe('ReactDOMEventListener', () => {
let React;
let ReactDOM;
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
});
describe('Propagation', () => {
it('should propagate events one level down', () => {
const mouseOut = jest.fn();
const onMouseOut = event => mouseOut(event.currentTarget);
const childContainer = document.createElement('div');
const parentContainer = document.createElement('div');
const childNode = ReactDOM.render(
<div onMouseOut={onMouseOut}>Child</div>,
childContainer,
);
const parentNode = ReactDOM.render(
<div onMouseOut={onMouseOut}>div</div>,
parentContainer,
);
parentNode.appendChild(childContainer);
document.body.appendChild(parentContainer);
try {
const nativeEvent = document.createEvent('Event');
nativeEvent.initEvent('mouseout', true, true);
childNode.dispatchEvent(nativeEvent);
expect(mouseOut).toBeCalled();
expect(mouseOut).toHaveBeenCalledTimes(2);
expect(mouseOut.mock.calls[0][0]).toEqual(childNode);
expect(mouseOut.mock.calls[1][0]).toEqual(parentNode);
} finally {
document.body.removeChild(parentContainer);
}
});
it('should propagate events two levels down', () => {
const mouseOut = jest.fn();
const onMouseOut = event => mouseOut(event.currentTarget);
const childContainer = document.createElement('div');
const parentContainer = document.createElement('div');
const grandParentContainer = document.createElement('div');
const childNode = ReactDOM.render(
<div onMouseOut={onMouseOut}>Child</div>,
childContainer,
);
const parentNode = ReactDOM.render(
<div onMouseOut={onMouseOut}>Parent</div>,
parentContainer,
);
const grandParentNode = ReactDOM.render(
<div onMouseOut={onMouseOut}>Parent</div>,
grandParentContainer,
);
parentNode.appendChild(childContainer);
grandParentNode.appendChild(parentContainer);
document.body.appendChild(grandParentContainer);
try {
const nativeEvent = document.createEvent('Event');
nativeEvent.initEvent('mouseout', true, true);
childNode.dispatchEvent(nativeEvent);
expect(mouseOut).toBeCalled();
expect(mouseOut).toHaveBeenCalledTimes(3);
expect(mouseOut.mock.calls[0][0]).toEqual(childNode);
expect(mouseOut.mock.calls[1][0]).toEqual(parentNode);
expect(mouseOut.mock.calls[2][0]).toEqual(grandParentNode);
} finally {
document.body.removeChild(grandParentContainer);
}
});
// Regression test for https://github.com/facebook/react/issues/1105
it('should not get confused by disappearing elements', () => {
const container = document.createElement('div');
document.body.appendChild(container);
try {
class MyComponent extends React.Component {
state = {clicked: false};
handleClick = () => {
this.setState({clicked: true});
};
componentDidMount() {
expect(ReactDOM.findDOMNode(this)).toBe(container.firstChild);
}
componentDidUpdate() {
expect(ReactDOM.findDOMNode(this)).toBe(container.firstChild);
}
render() {
if (this.state.clicked) {
return <span>clicked!</span>;
} else {
return (
<button onClick={this.handleClick}>not yet clicked</button>
);
}
}
}
ReactDOM.render(<MyComponent />, container);
container.firstChild.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
}),
);
expect(container.firstChild.textContent).toBe('clicked!');
} finally {
document.body.removeChild(container);
}
});
it('should batch between handlers from different roots', () => {
const mock = jest.fn();
const childContainer = document.createElement('div');
const handleChildMouseOut = () => {
ReactDOM.render(<div>1</div>, childContainer);
mock(childNode.textContent);
};
const parentContainer = document.createElement('div');
const handleParentMouseOut = () => {
ReactDOM.render(<div>2</div>, childContainer);
mock(childNode.textContent);
};
const childNode = ReactDOM.render(
<div onMouseOut={handleChildMouseOut}>Child</div>,
childContainer,
);
const parentNode = ReactDOM.render(
<div onMouseOut={handleParentMouseOut}>Parent</div>,
parentContainer,
);
parentNode.appendChild(childContainer);
document.body.appendChild(parentContainer);
try {
const nativeEvent = document.createEvent('Event');
nativeEvent.initEvent('mouseout', true, true);
childNode.dispatchEvent(nativeEvent);
// Child and parent should both call from event handlers.
expect(mock).toHaveBeenCalledTimes(2);
// The first call schedules a render of '1' into the 'Child'.
// However, we're batching so it isn't flushed yet.
expect(mock.mock.calls[0][0]).toBe('Child');
// As we have two roots, it means we have two event listeners.
// This also means we enter the event batching phase twice,
// flushing the child to be 1.
// We don't have any good way of knowing if another event will
// occur because another event handler might invoke
// stopPropagation() along the way. After discussions internally
// with Sebastian, it seems that for now over-flushing should
// be fine, especially as the new event system is a breaking
// change anyway. We can maybe revisit this later as part of
// the work to refine this in the scheduler (maybe by leveraging
// isInputPending?).
expect(mock.mock.calls[1][0]).toBe('1');
// By the time we leave the handler, the second update is flushed.
expect(childNode.textContent).toBe('2');
} finally {
document.body.removeChild(parentContainer);
}
});
});
it('should not fire duplicate events for a React DOM tree', () => {
const mouseOut = jest.fn();
const onMouseOut = event => mouseOut(event.target);
class Wrapper extends React.Component {
getInner = () => {
return this.refs.inner;
};
render() {
const inner = <div ref="inner">Inner</div>;
return (
<div>
<div onMouseOut={onMouseOut} id="outer">
{inner}
</div>
</div>
);
}
}
const container = document.createElement('div');
const instance = ReactDOM.render(<Wrapper />, container);
document.body.appendChild(container);
try {
const nativeEvent = document.createEvent('Event');
nativeEvent.initEvent('mouseout', true, true);
instance.getInner().dispatchEvent(nativeEvent);
expect(mouseOut).toBeCalled();
expect(mouseOut).toHaveBeenCalledTimes(1);
expect(mouseOut.mock.calls[0][0]).toEqual(instance.getInner());
} finally {
document.body.removeChild(container);
}
});
// Regression test for https://github.com/facebook/react/pull/12877
it('should not fire form events twice', () => {
const container = document.createElement('div');
document.body.appendChild(container);
const formRef = React.createRef();
const inputRef = React.createRef();
const handleInvalid = jest.fn();
const handleReset = jest.fn();
const handleSubmit = jest.fn();
ReactDOM.render(
<form ref={formRef} onReset={handleReset} onSubmit={handleSubmit}>
<input ref={inputRef} onInvalid={handleInvalid} />
</form>,
container,
);
inputRef.current.dispatchEvent(
new Event('invalid', {
// https://developer.mozilla.org/en-US/docs/Web/Events/invalid
bubbles: false,
}),
);
expect(handleInvalid).toHaveBeenCalledTimes(1);
formRef.current.dispatchEvent(
new Event('reset', {
// https://developer.mozilla.org/en-US/docs/Web/Events/reset
bubbles: true,
}),
);
expect(handleReset).toHaveBeenCalledTimes(1);
formRef.current.dispatchEvent(
new Event('submit', {
// https://developer.mozilla.org/en-US/docs/Web/Events/submit
bubbles: true,
}),
);
expect(handleSubmit).toHaveBeenCalledTimes(1);
formRef.current.dispatchEvent(
new Event('submit', {
// Might happen on older browsers.
bubbles: true,
}),
);
expect(handleSubmit).toHaveBeenCalledTimes(2); // It already fired in this test.
document.body.removeChild(container);
});
// This tests an implementation detail that submit/reset events are listened to
// at the document level, which is necessary for event replaying to work.
// They bubble in all modern browsers.
it('should not receive submit events if native, interim DOM handler prevents it', () => {
const container = document.createElement('div');
document.body.appendChild(container);
try {
const formRef = React.createRef();
const interimRef = React.createRef();
const handleSubmit = jest.fn();
const handleReset = jest.fn();
ReactDOM.render(
<div ref={interimRef}>
<form ref={formRef} onSubmit={handleSubmit} onReset={handleReset} />
</div>,
container,
);
interimRef.current.onsubmit = nativeEvent =>
nativeEvent.stopPropagation();
interimRef.current.onreset = nativeEvent => nativeEvent.stopPropagation();
formRef.current.dispatchEvent(
new Event('submit', {
// https://developer.mozilla.org/en-US/docs/Web/Events/submit
bubbles: true,
}),
);
formRef.current.dispatchEvent(
new Event('reset', {
// https://developer.mozilla.org/en-US/docs/Web/Events/reset
bubbles: true,
}),
);
expect(handleSubmit).not.toHaveBeenCalled();
expect(handleReset).not.toHaveBeenCalled();
} finally {
document.body.removeChild(container);
}
});
it('should dispatch loadstart only for media elements', () => {
const container = document.createElement('div');
document.body.appendChild(container);
try {
const imgRef = React.createRef();
const videoRef = React.createRef();
const handleImgLoadStart = jest.fn();
const handleVideoLoadStart = jest.fn();
ReactDOM.render(
<div>
<img ref={imgRef} onLoadStart={handleImgLoadStart} />
<video ref={videoRef} onLoadStart={handleVideoLoadStart} />
</div>,
container,
);
// Note for debugging: loadstart currently doesn't fire in Chrome.
// https://bugs.chromium.org/p/chromium/issues/detail?id=458851
imgRef.current.dispatchEvent(
new ProgressEvent('loadstart', {
bubbles: false,
}),
);
// As of the modern event system refactor, we now support
// this on <img>. The reason for this, is because we allow
// events to be attached to nodes regardless of if they
// necessary support them. This is a strange test, as this
// would never occur from normal browser behavior.
expect(handleImgLoadStart).toHaveBeenCalledTimes(1);
videoRef.current.dispatchEvent(
new ProgressEvent('loadstart', {
bubbles: false,
}),
);
expect(handleVideoLoadStart).toHaveBeenCalledTimes(1);
} finally {
document.body.removeChild(container);
}
});
it('should not attempt to listen to unnecessary events on the top level', () => {
const container = document.createElement('div');
document.body.appendChild(container);
const videoRef = React.createRef();
// We'll test this event alone.
const handleVideoPlay = jest.fn();
const handleVideoPlayDelegated = jest.fn();
const mediaEvents = {
onAbort() {},
onCanPlay() {},
onCanPlayThrough() {},
onDurationChange() {},
onEmptied() {},
onEncrypted() {},
onEnded() {},
onError() {},
onLoadedData() {},
onLoadedMetadata() {},
onLoadStart() {},
onPause() {},
onPlay() {},
onPlaying() {},
onProgress() {},
onRateChange() {},
onSeeked() {},
onSeeking() {},
onStalled() {},
onSuspend() {},
onTimeUpdate() {},
onVolumeChange() {},
onWaiting() {},
};
const originalDocAddEventListener = document.addEventListener;
const originalRootAddEventListener = container.addEventListener;
document.addEventListener = function(type) {
throw new Error(
`Did not expect to add a document-level listener for the "${type}" event.`,
);
};
container.addEventListener = function(type) {
if (type === 'mouseout' || type === 'mouseover') {
// We currently listen to it unconditionally.
return;
}
throw new Error(
`Did not expect to add a root-level listener for the "${type}" event.`,
);
};
try {
// We expect that mounting this tree will
// *not* attach handlers for any top-level events.
ReactDOM.render(
<div onPlay={handleVideoPlayDelegated}>
<video ref={videoRef} {...mediaEvents} onPlay={handleVideoPlay} />
<audio {...mediaEvents}>
<source {...mediaEvents} />
</audio>
</div>,
container,
);
// Also verify dispatching one of them works
videoRef.current.dispatchEvent(
new Event('play', {
bubbles: false,
}),
);
expect(handleVideoPlay).toHaveBeenCalledTimes(1);
// Unlike browsers, we delegate media events.
// (This doesn't make a lot of sense but it would be a breaking change not to.)
expect(handleVideoPlayDelegated).toHaveBeenCalledTimes(1);
} finally {
document.addEventListener = originalDocAddEventListener;
container.addEventListener = originalRootAddEventListener;
document.body.removeChild(container);
}
});
it('should dispatch load for embed elements', () => {
const container = document.createElement('div');
document.body.appendChild(container);
try {
const ref = React.createRef();
const handleLoad = jest.fn();
ReactDOM.render(
<div>
<embed ref={ref} onLoad={handleLoad} />
</div>,
container,
);
ref.current.dispatchEvent(
new ProgressEvent('load', {
bubbles: false,
}),
);
expect(handleLoad).toHaveBeenCalledTimes(1);
} finally {
document.body.removeChild(container);
}
});
// Unlike browsers, we delegate media events.
// (This doesn't make a lot of sense but it would be a breaking change not to.)
it('should delegate media events even without a direct listener', () => {
const container = document.createElement('div');
const ref = React.createRef();
const handleVideoPlayDelegated = jest.fn();
document.body.appendChild(container);
try {
ReactDOM.render(
<div onPlay={handleVideoPlayDelegated}>
{/* Intentionally no handler on the target: */}
<video ref={ref} />
</div>,
container,
);
ref.current.dispatchEvent(
new Event('play', {
bubbles: false,
}),
);
// Regression test: ensure React tree delegation still works
// even if the actual DOM element did not have a handler.
expect(handleVideoPlayDelegated).toHaveBeenCalledTimes(1);
} finally {
document.body.removeChild(container);
}
});
it('should delegate dialog events even without a direct listener', () => {
const container = document.createElement('div');
const ref = React.createRef();
const onCancel = jest.fn();
const onClose = jest.fn();
document.body.appendChild(container);
try {
ReactDOM.render(
<div onCancel={onCancel} onClose={onClose}>
{/* Intentionally no handler on the target: */}
<dialog ref={ref} />
</div>,
container,
);
ref.current.dispatchEvent(
new Event('close', {
bubbles: false,
}),
);
ref.current.dispatchEvent(
new Event('cancel', {
bubbles: false,
}),
);
// Regression test: ensure React tree delegation still works
// even if the actual DOM element did not have a handler.
expect(onCancel).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledTimes(1);
} finally {
document.body.removeChild(container);
}
});
it('should bubble non-native bubbling events', () => {
const container = document.createElement('div');
const ref = React.createRef();
const onPlay = jest.fn();
const onCancel = jest.fn();
const onClose = jest.fn();
const onToggle = jest.fn();
document.body.appendChild(container);
try {
ReactDOM.render(
<div
onPlay={onPlay}
onCancel={onCancel}
onClose={onClose}
onToggle={onToggle}>
<div
ref={ref}
onPlay={onPlay}
onCancel={onCancel}
onClose={onClose}
onToggle={onToggle}
/>
</div>,
container,
);
ref.current.dispatchEvent(
new Event('play', {
bubbles: false,
}),
);
ref.current.dispatchEvent(
new Event('cancel', {
bubbles: false,
}),
);
ref.current.dispatchEvent(
new Event('close', {
bubbles: false,
}),
);
ref.current.dispatchEvent(
new Event('toggle', {
bubbles: false,
}),
);
// Regression test: ensure we still emulate bubbling with non-bubbling
// media
expect(onPlay).toHaveBeenCalledTimes(2);
expect(onCancel).toHaveBeenCalledTimes(2);
expect(onClose).toHaveBeenCalledTimes(2);
expect(onToggle).toHaveBeenCalledTimes(2);
} finally {
document.body.removeChild(container);
}
});
it('should handle non-bubbling capture events correctly', () => {
const container = document.createElement('div');
const innerRef = React.createRef();
const outerRef = React.createRef();
const onPlayCapture = jest.fn(e => log.push(e.currentTarget));
const log = [];
document.body.appendChild(container);
try {
ReactDOM.render(
<div ref={outerRef} onPlayCapture={onPlayCapture}>
<div onPlayCapture={onPlayCapture}>
<div ref={innerRef} onPlayCapture={onPlayCapture} />
</div>
</div>,
container,
);
innerRef.current.dispatchEvent(
new Event('play', {
bubbles: false,
}),
);
expect(onPlayCapture).toHaveBeenCalledTimes(3);
expect(log).toEqual([
outerRef.current,
outerRef.current.firstChild,
innerRef.current,
]);
outerRef.current.dispatchEvent(
new Event('play', {
bubbles: false,
}),
);
expect(onPlayCapture).toHaveBeenCalledTimes(4);
expect(log).toEqual([
outerRef.current,
outerRef.current.firstChild,
innerRef.current,
outerRef.current,
]);
} finally {
document.body.removeChild(container);
}
});
// We're moving towards aligning more closely with the browser.
// Currently we emulate bubbling for all non-bubbling events except scroll.
// We may expand this list in the future, removing emulated bubbling altogether.
it('should not emulate bubbling of scroll events', () => {
const container = document.createElement('div');
const ref = React.createRef();
const log = [];
const onScroll = jest.fn(e =>
log.push(['bubble', e.currentTarget.className]),
);
const onScrollCapture = jest.fn(e =>
log.push(['capture', e.currentTarget.className]),
);
document.body.appendChild(container);
try {
ReactDOM.render(
<div
className="grand"
onScroll={onScroll}
onScrollCapture={onScrollCapture}>
<div
className="parent"
onScroll={onScroll}
onScrollCapture={onScrollCapture}>
<div
className="child"
onScroll={onScroll}
onScrollCapture={onScrollCapture}
ref={ref}
/>
</div>
</div>,
container,
);
ref.current.dispatchEvent(
new Event('scroll', {
bubbles: false,
}),
);
if (gate(flags => flags.disableOnScrollBubbling)) {
expect(log).toEqual([
['capture', 'grand'],
['capture', 'parent'],
['capture', 'child'],
['bubble', 'child'],
]);
} else {
expect(log).toEqual([
['capture', 'grand'],
['capture', 'parent'],
['capture', 'child'],
['bubble', 'child'],
['bubble', 'parent'],
['bubble', 'grand'],
]);
}
} finally {
document.body.removeChild(container);
}
});
// We're moving towards aligning more closely with the browser.
// Currently we emulate bubbling for all non-bubbling events except scroll.
// We may expand this list in the future, removing emulated bubbling altogether.
it('should not emulate bubbling of scroll events (no own handler)', () => {
const container = document.createElement('div');
const ref = React.createRef();
const log = [];
const onScroll = jest.fn(e =>
log.push(['bubble', e.currentTarget.className]),
);
const onScrollCapture = jest.fn(e =>
log.push(['capture', e.currentTarget.className]),
);
document.body.appendChild(container);
try {
ReactDOM.render(
<div
className="grand"
onScroll={onScroll}
onScrollCapture={onScrollCapture}>
<div
className="parent"
onScroll={onScroll}
onScrollCapture={onScrollCapture}>
{/* Intentionally no handler on the child: */}
<div className="child" ref={ref} />
</div>
</div>,
container,
);
ref.current.dispatchEvent(
new Event('scroll', {
bubbles: false,
}),
);
expect(log).toEqual([
['capture', 'grand'],
['capture', 'parent'],
]);
} finally {
document.body.removeChild(container);
}
});
});