forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChangeEventPlugin-test.js
771 lines (667 loc) · 23.9 KB
/
ChangeEventPlugin-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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
/**
* 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';
let React;
let ReactDOM;
let TestUtils;
let ReactFeatureFlags;
let Scheduler;
const setUntrackedChecked = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype,
'checked',
).set;
const setUntrackedValue = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype,
'value',
).set;
const setUntrackedTextareaValue = Object.getOwnPropertyDescriptor(
HTMLTextAreaElement.prototype,
'value',
).set;
describe('ChangeEventPlugin', () => {
let container;
beforeEach(() => {
jest.resetModules();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
// TODO pull this into helper method, reduce repetition.
// mock the browser APIs which are used in schedule:
// - calling 'window.postMessage' should actually fire postmessage handlers
const originalAddEventListener = global.addEventListener;
let postMessageCallback;
global.addEventListener = function(eventName, callback, useCapture) {
if (eventName === 'message') {
postMessageCallback = callback;
} else {
originalAddEventListener(eventName, callback, useCapture);
}
};
global.postMessage = function(messageKey, targetOrigin) {
const postMessageEvent = {source: window, data: messageKey};
if (postMessageCallback) {
postMessageCallback(postMessageEvent);
}
};
React = require('react');
ReactDOM = require('react-dom');
TestUtils = require('react-dom/test-utils');
Scheduler = require('scheduler');
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
// We try to avoid firing "duplicate" React change events.
// However, to tell which events are "duplicates" and should be ignored,
// we are tracking the "current" input value, and only respect events
// that occur after it changes. In most of these tests, we verify that we
// keep track of the "current" value and only fire events when it changes.
// See https://github.com/facebook/react/pull/5746.
it('should consider initial text value to be current', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const node = ReactDOM.render(
<input type="text" onChange={cb} defaultValue="foo" />,
container,
);
node.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
node.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
if (ReactFeatureFlags.disableInputAttributeSyncing) {
// TODO: figure out why. This might be a bug.
expect(called).toBe(1);
} else {
// There should be no React change events because the value stayed the same.
expect(called).toBe(0);
}
});
it('should consider initial text value to be current (capture)', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const node = ReactDOM.render(
<input type="text" onChangeCapture={cb} defaultValue="foo" />,
container,
);
node.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
node.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
if (ReactFeatureFlags.disableInputAttributeSyncing) {
// TODO: figure out why. This might be a bug.
expect(called).toBe(1);
} else {
// There should be no React change events because the value stayed the same.
expect(called).toBe(0);
}
});
it('should consider initial checkbox checked=true to be current', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const node = ReactDOM.render(
<input type="checkbox" onChange={cb} defaultChecked={true} />,
container,
);
// Secretly, set `checked` to false, so that dispatching the `click` will
// make it `true` again. Thus, at the time of the event, React should not
// consider it a change from the initial `true` value.
setUntrackedChecked.call(node, false);
node.dispatchEvent(
new MouseEvent('click', {bubbles: true, cancelable: true}),
);
// There should be no React change events because the value stayed the same.
expect(called).toBe(0);
});
it('should consider initial checkbox checked=false to be current', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const node = ReactDOM.render(
<input type="checkbox" onChange={cb} defaultChecked={false} />,
container,
);
// Secretly, set `checked` to true, so that dispatching the `click` will
// make it `false` again. Thus, at the time of the event, React should not
// consider it a change from the initial `false` value.
setUntrackedChecked.call(node, true);
node.dispatchEvent(
new MouseEvent('click', {bubbles: true, cancelable: true}),
);
// There should be no React change events because the value stayed the same.
expect(called).toBe(0);
});
it('should fire change for checkbox input', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const node = ReactDOM.render(
<input type="checkbox" onChange={cb} />,
container,
);
expect(node.checked).toBe(false);
node.dispatchEvent(
new MouseEvent('click', {bubbles: true, cancelable: true}),
);
// Note: unlike with text input events, dispatching `click` actually
// toggles the checkbox and updates its `checked` value.
expect(node.checked).toBe(true);
expect(called).toBe(1);
expect(node.checked).toBe(true);
node.dispatchEvent(
new MouseEvent('click', {bubbles: true, cancelable: true}),
);
expect(node.checked).toBe(false);
expect(called).toBe(2);
});
it('should not fire change setting the value programmatically', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const input = ReactDOM.render(
<input type="text" defaultValue="foo" onChange={cb} />,
container,
);
// Set it programmatically.
input.value = 'bar';
// Even if a DOM input event fires, React sees that the real input value now
// ('bar') is the same as the "current" one we already recorded.
input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
expect(input.value).toBe('bar');
// In this case we don't expect to get a React event.
expect(called).toBe(0);
// However, we can simulate user typing by calling the underlying setter.
setUntrackedValue.call(input, 'foo');
// Now, when the event fires, the real input value ('foo') differs from the
// "current" one we previously recorded ('bar').
input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
expect(input.value).toBe('foo');
// In this case React should fire an event for it.
expect(called).toBe(1);
// Verify again that extra events without real changes are ignored.
input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
expect(called).toBe(1);
});
it('should not distinguish equal string and number values', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const input = ReactDOM.render(
<input type="text" defaultValue="42" onChange={cb} />,
container,
);
// When we set `value` as a property, React updates the "current" value
// that it tracks internally. The "current" value is later used to determine
// whether a change event is a duplicate or not.
// Even though we set value to a number, we still shouldn't get a change
// event because as a string, it's equal to the initial value ('42').
input.value = 42;
input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
expect(input.value).toBe('42');
expect(called).toBe(0);
});
// See a similar input test above for a detailed description of why.
it('should not fire change when setting checked programmatically', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const input = ReactDOM.render(
<input type="checkbox" onChange={cb} defaultChecked={false} />,
container,
);
// Set the value, updating the "current" value that React tracks to true.
input.checked = true;
// Under the hood, uncheck the box so that the click will "check" it again.
setUntrackedChecked.call(input, false);
input.click();
expect(input.checked).toBe(true);
// We don't expect a React event because at the time of the click, the real
// checked value (true) was the same as the last recorded "current" value
// (also true).
expect(called).toBe(0);
// However, simulating a normal click should fire a React event because the
// real value (false) would have changed from the last tracked value (true).
input.click();
expect(called).toBe(1);
});
it('should unmount', () => {
const input = ReactDOM.render(<input />, container);
ReactDOM.unmountComponentAtNode(container);
});
it('should only fire change for checked radio button once', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const input = ReactDOM.render(
<input type="radio" onChange={cb} />,
container,
);
setUntrackedChecked.call(input, true);
input.dispatchEvent(new Event('click', {bubbles: true, cancelable: true}));
input.dispatchEvent(new Event('click', {bubbles: true, cancelable: true}));
expect(called).toBe(1);
});
it('should track radio button cousins in a group', () => {
let called1 = 0;
let called2 = 0;
function cb1(e) {
called1++;
expect(e.type).toBe('change');
}
function cb2(e) {
called2++;
expect(e.type).toBe('change');
}
const div = ReactDOM.render(
<div>
<input type="radio" name="group" onChange={cb1} />
<input type="radio" name="group" onChange={cb2} />
</div>,
container,
);
const option1 = div.childNodes[0];
const option2 = div.childNodes[1];
// Select first option.
option1.click();
expect(called1).toBe(1);
expect(called2).toBe(0);
// Select second option.
option2.click();
expect(called1).toBe(1);
expect(called2).toBe(1);
// Select the first option.
// It should receive the React change event again.
option1.click();
expect(called1).toBe(2);
expect(called2).toBe(1);
});
it('should deduplicate input value change events', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
let input;
['text', 'number', 'range'].forEach(type => {
called = 0;
input = ReactDOM.render(<input type={type} onChange={cb} />, container);
// Should be ignored (no change):
input.dispatchEvent(
new Event('change', {bubbles: true, cancelable: true}),
);
setUntrackedValue.call(input, '42');
input.dispatchEvent(
new Event('change', {bubbles: true, cancelable: true}),
);
// Should be ignored (no change):
input.dispatchEvent(
new Event('change', {bubbles: true, cancelable: true}),
);
expect(called).toBe(1);
ReactDOM.unmountComponentAtNode(container);
called = 0;
input = ReactDOM.render(<input type={type} onChange={cb} />, container);
// Should be ignored (no change):
input.dispatchEvent(
new Event('input', {bubbles: true, cancelable: true}),
);
setUntrackedValue.call(input, '42');
input.dispatchEvent(
new Event('input', {bubbles: true, cancelable: true}),
);
// Should be ignored (no change):
input.dispatchEvent(
new Event('input', {bubbles: true, cancelable: true}),
);
expect(called).toBe(1);
ReactDOM.unmountComponentAtNode(container);
called = 0;
input = ReactDOM.render(<input type={type} onChange={cb} />, container);
// Should be ignored (no change):
input.dispatchEvent(
new Event('change', {bubbles: true, cancelable: true}),
);
setUntrackedValue.call(input, '42');
input.dispatchEvent(
new Event('input', {bubbles: true, cancelable: true}),
);
// Should be ignored (no change):
input.dispatchEvent(
new Event('change', {bubbles: true, cancelable: true}),
);
expect(called).toBe(1);
ReactDOM.unmountComponentAtNode(container);
});
});
it('should listen for both change and input events when supported', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const input = ReactDOM.render(
<input type="range" onChange={cb} />,
container,
);
setUntrackedValue.call(input, 10);
input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
setUntrackedValue.call(input, 20);
input.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
expect(called).toBe(2);
});
it('should only fire events when the value changes for range inputs', () => {
let called = 0;
function cb(e) {
called++;
expect(e.type).toBe('change');
}
const input = ReactDOM.render(
<input type="range" onChange={cb} />,
container,
);
setUntrackedValue.call(input, '40');
input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
input.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
setUntrackedValue.call(input, 'foo');
input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
input.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
expect(called).toBe(2);
});
it('does not crash for nodes with custom value property', () => {
let originalCreateElement;
// https://github.com/facebook/react/issues/10196
try {
originalCreateElement = document.createElement;
document.createElement = function() {
const node = originalCreateElement.apply(this, arguments);
Object.defineProperty(node, 'value', {
get() {},
set() {},
});
return node;
};
const div = document.createElement('div');
// Mount
const node = ReactDOM.render(<input type="text" />, div);
// Update
ReactDOM.render(<input type="text" />, div);
// Change
node.dispatchEvent(
new Event('change', {bubbles: true, cancelable: true}),
);
// Unmount
ReactDOM.unmountComponentAtNode(div);
} finally {
document.createElement = originalCreateElement;
}
});
describe('concurrent mode', () => {
// @gate experimental
it('text input', () => {
const root = ReactDOM.unstable_createRoot(container);
let input;
class ControlledInput extends React.Component {
state = {value: 'initial'};
onChange = event => this.setState({value: event.target.value});
render() {
Scheduler.unstable_yieldValue(`render: ${this.state.value}`);
const controlledValue =
this.state.value === 'changed' ? 'changed [!]' : this.state.value;
return (
<input
ref={el => (input = el)}
type="text"
value={controlledValue}
onChange={this.onChange}
/>
);
}
}
// Initial mount. Test that this is async.
root.render(<ControlledInput />);
// Should not have flushed yet.
expect(Scheduler).toHaveYielded([]);
expect(input).toBe(undefined);
// Flush callbacks.
expect(Scheduler).toFlushAndYield(['render: initial']);
expect(input.value).toBe('initial');
// Trigger a change event.
setUntrackedValue.call(input, 'changed');
input.dispatchEvent(
new Event('input', {bubbles: true, cancelable: true}),
);
// Change should synchronously flush
expect(Scheduler).toHaveYielded(['render: changed']);
// Value should be the controlled value, not the original one
expect(input.value).toBe('changed [!]');
});
// @gate experimental
it('checkbox input', () => {
const root = ReactDOM.unstable_createRoot(container);
let input;
class ControlledInput extends React.Component {
state = {checked: false};
onChange = event => {
this.setState({checked: event.target.checked});
};
render() {
Scheduler.unstable_yieldValue(`render: ${this.state.checked}`);
const controlledValue = this.props.reverse
? !this.state.checked
: this.state.checked;
return (
<input
ref={el => (input = el)}
type="checkbox"
checked={controlledValue}
onChange={this.onChange}
/>
);
}
}
// Initial mount. Test that this is async.
root.render(<ControlledInput reverse={false} />);
// Should not have flushed yet.
expect(Scheduler).toHaveYielded([]);
expect(input).toBe(undefined);
// Flush callbacks.
expect(Scheduler).toFlushAndYield(['render: false']);
expect(input.checked).toBe(false);
// Trigger a change event.
input.dispatchEvent(
new MouseEvent('click', {bubbles: true, cancelable: true}),
);
// Change should synchronously flush
expect(Scheduler).toHaveYielded(['render: true']);
expect(input.checked).toBe(true);
// Now let's make sure we're using the controlled value.
root.render(<ControlledInput reverse={true} />);
expect(Scheduler).toFlushAndYield(['render: true']);
// Trigger another change event.
input.dispatchEvent(
new MouseEvent('click', {bubbles: true, cancelable: true}),
);
// Change should synchronously flush
expect(Scheduler).toHaveYielded(['render: true']);
expect(input.checked).toBe(false);
});
// @gate experimental
it('textarea', () => {
const root = ReactDOM.unstable_createRoot(container);
let textarea;
class ControlledTextarea extends React.Component {
state = {value: 'initial'};
onChange = event => this.setState({value: event.target.value});
render() {
Scheduler.unstable_yieldValue(`render: ${this.state.value}`);
const controlledValue =
this.state.value === 'changed' ? 'changed [!]' : this.state.value;
return (
<textarea
ref={el => (textarea = el)}
type="text"
value={controlledValue}
onChange={this.onChange}
/>
);
}
}
// Initial mount. Test that this is async.
root.render(<ControlledTextarea />);
// Should not have flushed yet.
expect(Scheduler).toHaveYielded([]);
expect(textarea).toBe(undefined);
// Flush callbacks.
expect(Scheduler).toFlushAndYield(['render: initial']);
expect(textarea.value).toBe('initial');
// Trigger a change event.
setUntrackedTextareaValue.call(textarea, 'changed');
textarea.dispatchEvent(
new Event('input', {bubbles: true, cancelable: true}),
);
// Change should synchronously flush
expect(Scheduler).toHaveYielded(['render: changed']);
// Value should be the controlled value, not the original one
expect(textarea.value).toBe('changed [!]');
});
// @gate experimental
it('parent of input', () => {
const root = ReactDOM.unstable_createRoot(container);
let input;
class ControlledInput extends React.Component {
state = {value: 'initial'};
onChange = event => this.setState({value: event.target.value});
render() {
Scheduler.unstable_yieldValue(`render: ${this.state.value}`);
const controlledValue =
this.state.value === 'changed' ? 'changed [!]' : this.state.value;
return (
<div onChange={this.onChange}>
<input
ref={el => (input = el)}
type="text"
value={controlledValue}
onChange={() => {
// Does nothing. Parent handler is responsible for updating.
}}
/>
</div>
);
}
}
// Initial mount. Test that this is async.
root.render(<ControlledInput />);
// Should not have flushed yet.
expect(Scheduler).toHaveYielded([]);
expect(input).toBe(undefined);
// Flush callbacks.
expect(Scheduler).toFlushAndYield(['render: initial']);
expect(input.value).toBe('initial');
// Trigger a change event.
setUntrackedValue.call(input, 'changed');
input.dispatchEvent(
new Event('input', {bubbles: true, cancelable: true}),
);
// Change should synchronously flush
expect(Scheduler).toHaveYielded(['render: changed']);
// Value should be the controlled value, not the original one
expect(input.value).toBe('changed [!]');
});
// @gate experimental
it('is sync for non-input events', async () => {
const root = ReactDOM.unstable_createRoot(container);
let input;
class ControlledInput extends React.Component {
state = {value: 'initial'};
onChange = event => this.setState({value: event.target.value});
reset = () => {
this.setState({value: ''});
};
render() {
Scheduler.unstable_yieldValue(`render: ${this.state.value}`);
const controlledValue =
this.state.value === 'changed' ? 'changed [!]' : this.state.value;
return (
<input
ref={el => (input = el)}
type="text"
value={controlledValue}
onChange={this.onChange}
onClick={this.reset}
/>
);
}
}
// Initial mount. Test that this is async.
root.render(<ControlledInput />);
// Should not have flushed yet.
expect(Scheduler).toHaveYielded([]);
expect(input).toBe(undefined);
// Flush callbacks.
expect(Scheduler).toFlushAndYield(['render: initial']);
expect(input.value).toBe('initial');
// Trigger a click event
input.dispatchEvent(
new Event('click', {bubbles: true, cancelable: true}),
);
// Flush microtask queue.
await null;
expect(Scheduler).toHaveYielded(['render: ']);
expect(input.value).toBe('');
});
// @gate experimental
it('mouse enter/leave should be user-blocking but not discrete', async () => {
const {unstable_concurrentAct: act} = TestUtils;
const {useState} = React;
const root = ReactDOM.unstable_createRoot(container);
const target = React.createRef(null);
function Foo() {
const [isHover, setHover] = useState(false);
return (
<div
ref={target}
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}>
{isHover ? 'hovered' : 'not hovered'}
</div>
);
}
await act(async () => {
root.render(<Foo />);
});
expect(container.textContent).toEqual('not hovered');
await act(async () => {
const mouseOverEvent = document.createEvent('MouseEvents');
mouseOverEvent.initEvent('mouseover', true, true);
target.current.dispatchEvent(mouseOverEvent);
// 3s should be enough to expire the updates
Scheduler.unstable_advanceTime(3000);
expect(Scheduler).toFlushExpired([]);
expect(container.textContent).toEqual('hovered');
});
});
});
});