-
Notifications
You must be signed in to change notification settings - Fork 47k
/
ReactDOMServerIntegration-test.js
2853 lines (2516 loc) · 99.7 KB
/
ReactDOMServerIntegration-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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* 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 ExecutionEnvironment;
let PropTypes;
let React;
let ReactDOM;
let ReactDOMServer;
let ReactTestUtils;
const stream = require('stream');
const TEXT_NODE_TYPE = 3;
// Helper functions for rendering tests
// ====================================
// promisified version of ReactDOM.render()
function asyncReactDOMRender(reactElement, domElement, forceHydrate) {
return new Promise(resolve => {
if (forceHydrate) {
ReactDOM.hydrate(reactElement, domElement);
} else {
ReactDOM.render(reactElement, domElement);
}
// We can't use the callback for resolution because that will not catch
// errors. They're thrown.
resolve();
});
}
// performs fn asynchronously and expects count errors logged to console.error.
// will fail the test if the count of errors logged is not equal to count.
async function expectErrors(fn, count) {
if (console.error.calls && console.error.calls.reset) {
console.error.calls.reset();
} else {
spyOn(console, 'error');
}
const result = await fn();
if (
console.error.calls.count() !== count &&
console.error.calls.count() !== 0
) {
console.log(
`We expected ${count} warning(s), but saw ${console.error.calls.count()} warning(s).`,
);
if (console.error.calls.count() > 0) {
console.log(`We saw these warnings:`);
for (var i = 0; i < console.error.calls.count(); i++) {
console.log(console.error.calls.argsFor(i)[0]);
}
}
}
expectDev(console.error.calls.count()).toBe(count);
return result;
}
// renders the reactElement into domElement, and expects a certain number of errors.
// returns a Promise that resolves when the render is complete.
function renderIntoDom(reactElement, domElement, forceHydrate, errorCount = 0) {
return expectErrors(async () => {
ExecutionEnvironment.canUseDOM = true;
await asyncReactDOMRender(reactElement, domElement, forceHydrate);
ExecutionEnvironment.canUseDOM = false;
return domElement.firstChild;
}, errorCount);
}
async function renderIntoString(reactElement, errorCount = 0) {
return await expectErrors(
() =>
new Promise(resolve =>
resolve(ReactDOMServer.renderToString(reactElement)),
),
errorCount,
);
}
// Renders text using SSR and then stuffs it into a DOM node; returns the DOM
// element that corresponds with the reactElement.
// Does not render on client or perform client-side revival.
async function serverRender(reactElement, errorCount = 0) {
const markup = await renderIntoString(reactElement, errorCount);
var domElement = document.createElement('div');
domElement.innerHTML = markup;
return domElement.firstChild;
}
// this just drains a readable piped into it to a string, which can be accessed
// via .buffer.
class DrainWritable extends stream.Writable {
constructor(options) {
super(options);
this.buffer = '';
}
_write(chunk, encoding, cb) {
this.buffer += chunk;
cb();
}
}
async function renderIntoStream(reactElement, errorCount = 0) {
return await expectErrors(
() =>
new Promise(resolve => {
let writable = new DrainWritable();
ReactDOMServer.renderToNodeStream(reactElement).pipe(writable);
writable.on('finish', () => resolve(writable.buffer));
}),
errorCount,
);
}
// Renders text using node stream SSR and then stuffs it into a DOM node;
// returns the DOM element that corresponds with the reactElement.
// Does not render on client or perform client-side revival.
async function streamRender(reactElement, errorCount = 0) {
const markup = await renderIntoStream(reactElement, errorCount);
var domElement = document.createElement('div');
domElement.innerHTML = markup;
return domElement.firstChild;
}
const clientCleanRender = (element, errorCount = 0) => {
const div = document.createElement('div');
return renderIntoDom(element, div, false, errorCount);
};
const clientRenderOnServerString = async (element, errorCount = 0) => {
const markup = await renderIntoString(element, errorCount);
resetModules();
var domElement = document.createElement('div');
domElement.innerHTML = markup;
let serverNode = domElement.firstChild;
const firstClientNode = await renderIntoDom(
element,
domElement,
true,
errorCount,
);
let clientNode = firstClientNode;
// Make sure all top level nodes match up
while (serverNode || clientNode) {
expect(serverNode != null).toBe(true);
expect(clientNode != null).toBe(true);
expect(clientNode.nodeType).toBe(serverNode.nodeType);
// Assert that the DOM element hasn't been replaced.
// Note that we cannot use expect(serverNode).toBe(clientNode) because
// of jest bug #1772.
expect(serverNode === clientNode).toBe(true);
serverNode = serverNode.nextSibling;
clientNode = clientNode.nextSibling;
}
return firstClientNode;
};
function BadMarkupExpected() {}
const clientRenderOnBadMarkup = async (element, errorCount = 0) => {
// First we render the top of bad mark up.
var domElement = document.createElement('div');
domElement.innerHTML =
'<div id="badIdWhichWillCauseMismatch" data-reactroot="" data-reactid="1"></div>';
await renderIntoDom(element, domElement, true, errorCount + 1);
// This gives us the resulting text content.
var hydratedTextContent = domElement.textContent;
// Next we render the element into a clean DOM node client side.
const cleanDomElement = document.createElement('div');
ExecutionEnvironment.canUseDOM = true;
await asyncReactDOMRender(element, cleanDomElement, true);
ExecutionEnvironment.canUseDOM = false;
// This gives us the expected text content.
const cleanTextContent = cleanDomElement.textContent;
// The only guarantee is that text content has been patched up if needed.
expect(hydratedTextContent).toBe(cleanTextContent);
// Abort any further expects. All bets are off at this point.
throw new BadMarkupExpected();
};
// runs a DOM rendering test as four different tests, with four different rendering
// scenarios:
// -- render to string on server
// -- render on client without any server markup "clean client render"
// -- render on client on top of good server-generated string markup
// -- render on client on top of bad server-generated markup
//
// testFn is a test that has one arg, which is a render function. the render
// function takes in a ReactElement and an optional expected error count and
// returns a promise of a DOM Element.
//
// You should only perform tests that examine the DOM of the results of
// render; you should not depend on the interactivity of the returned DOM element,
// as that will not work in the server string scenario.
function itRenders(desc, testFn) {
it(`renders ${desc} with server string render`, () => testFn(serverRender));
it(`renders ${desc} with server stream render`, () => testFn(streamRender));
itClientRenders(desc, testFn);
}
// run testFn in three different rendering scenarios:
// -- render on client without any server markup "clean client render"
// -- render on client on top of good server-generated string markup
// -- render on client on top of bad server-generated markup
//
// testFn is a test that has one arg, which is a render function. the render
// function takes in a ReactElement and an optional expected error count and
// returns a promise of a DOM Element.
//
// Since all of the renders in this function are on the client, you can test interactivity,
// unlike with itRenders.
function itClientRenders(desc, testFn) {
it(`renders ${desc} with clean client render`, () =>
testFn(clientCleanRender));
it(`renders ${desc} with client render on top of good server markup`, () =>
testFn(clientRenderOnServerString));
it(`renders ${desc} with client render on top of bad server markup`, async () => {
try {
await testFn(clientRenderOnBadMarkup);
} catch (x) {
// We expect this to trigger the BadMarkupExpected rejection.
if (!(x instanceof BadMarkupExpected)) {
// If not, rethrow.
throw x;
}
}
});
}
function itThrows(desc, testFn, partialMessage) {
it(`throws ${desc}`, () => {
return testFn().then(
() => expect(false).toBe('The promise resolved and should not have.'),
err => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toContain(partialMessage);
},
);
});
}
function itThrowsWhenRendering(desc, testFn, partialMessage) {
itThrows(
`when rendering ${desc} with server string render`,
() => testFn(serverRender),
partialMessage,
);
itThrows(
`when rendering ${desc} with clean client render`,
() => testFn(clientCleanRender),
partialMessage,
);
// we subtract one from the warning count here because the throw means that it won't
// get the usual markup mismatch warning.
itThrows(
`when rendering ${desc} with client render on top of bad server markup`,
() =>
testFn((element, warningCount = 0) =>
clientRenderOnBadMarkup(element, warningCount - 1),
),
partialMessage,
);
}
// renders serverElement to a string, sticks it into a DOM element, and then
// tries to render clientElement on top of it. shouldMatch is a boolean
// telling whether we should expect the markup to match or not.
async function testMarkupMatch(serverElement, clientElement, shouldMatch) {
const domElement = await serverRender(serverElement);
resetModules();
return renderIntoDom(
clientElement,
domElement.parentNode,
true,
shouldMatch ? 0 : 1,
);
}
// expects that rendering clientElement on top of a server-rendered
// serverElement does NOT raise a markup mismatch warning.
function expectMarkupMatch(serverElement, clientElement) {
return testMarkupMatch(serverElement, clientElement, true);
}
// expects that rendering clientElement on top of a server-rendered
// serverElement DOES raise a markup mismatch warning.
function expectMarkupMismatch(serverElement, clientElement) {
return testMarkupMatch(serverElement, clientElement, false);
}
// When there is a test that renders on server and then on client and expects a logged
// error, you want to see the error show up both on server and client. Unfortunately,
// React refuses to issue the same error twice to avoid clogging up the console.
// To get around this, we must reload React modules in between server and client render.
function resetModules() {
// First, reset the modules to load the client renderer.
jest.resetModuleRegistry();
// TODO: can we express this test with only public API?
ExecutionEnvironment = require('ExecutionEnvironment');
PropTypes = require('prop-types');
React = require('react');
ReactDOM = require('react-dom');
ReactTestUtils = require('react-dom/test-utils');
// Now we reset the modules again to load the server renderer.
// Resetting is important because we want to avoid any shared state
// influencing the tests.
jest.resetModuleRegistry();
ReactDOMServer = require('react-dom/server');
}
describe('ReactDOMServerIntegration', () => {
beforeEach(() => {
resetModules();
ExecutionEnvironment.canUseDOM = false;
});
describe('basic rendering', function() {
itRenders('a blank div', async render => {
const e = await render(<div />);
expect(e.tagName).toBe('DIV');
});
itRenders('a self-closing tag', async render => {
const e = await render(<br />);
expect(e.tagName).toBe('BR');
});
itRenders('a self-closing tag as a child', async render => {
const e = await render(<div><br /></div>);
expect(e.childNodes.length).toBe(1);
expect(e.firstChild.tagName).toBe('BR');
});
itRenders('a string', async render => {
let e = await render('Hello');
expect(e.nodeType).toBe(3);
expect(e.nodeValue).toMatch('Hello');
});
itRenders('a number', async render => {
let e = await render(42);
expect(e.nodeType).toBe(3);
expect(e.nodeValue).toMatch('42');
});
itRenders('an array with one child', async render => {
let e = await render([<div key={1}>text1</div>]);
let parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
});
itRenders('an array with several children', async render => {
let Header = props => {
return <p>header</p>;
};
let Footer = props => {
return [<h2 key={1}>footer</h2>, <h3 key={2}>about</h3>];
};
let e = await render([
<div key={1}>text1</div>,
<span key={2}>text2</span>,
<Header key={3} />,
<Footer key={4} />,
]);
let parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
expect(parent.childNodes[1].tagName).toBe('SPAN');
expect(parent.childNodes[2].tagName).toBe('P');
expect(parent.childNodes[3].tagName).toBe('H2');
expect(parent.childNodes[4].tagName).toBe('H3');
});
itRenders('a nested array', async render => {
let e = await render([
[<div key={1}>text1</div>],
<span key={1}>text2</span>,
[[[null, <p key={1} />], false]],
]);
let parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV');
expect(parent.childNodes[1].tagName).toBe('SPAN');
expect(parent.childNodes[2].tagName).toBe('P');
});
itRenders('an iterable', async render => {
const threeDivIterable = {
'@@iterator': function() {
var i = 0;
return {
next: function() {
if (i++ < 3) {
return {value: <div key={i} />, done: false};
} else {
return {value: undefined, done: true};
}
},
};
},
};
let e = await render(threeDivIterable);
let parent = e.parentNode;
expect(parent.childNodes.length).toBe(3);
expect(parent.childNodes[0].tagName).toBe('DIV');
expect(parent.childNodes[1].tagName).toBe('DIV');
expect(parent.childNodes[2].tagName).toBe('DIV');
});
itRenders('emptyish values', async render => {
let e = await render(0);
expect(e.nodeType).toBe(TEXT_NODE_TYPE);
expect(e.nodeValue).toMatch('0');
// Empty string is special because client renders a node
// but server returns empty HTML. So we compare parent text.
expect((await render(<div>{''}</div>)).textContent).toBe('');
expect(await render([])).toBe(null);
expect(await render(false)).toBe(null);
expect(await render(true)).toBe(null);
expect(await render(undefined)).toBe(null);
expect(await render([[[false]], undefined])).toBe(null);
});
});
describe('property to attribute mapping', function() {
describe('string properties', function() {
itRenders('simple numbers', async render => {
const e = await render(<div width={30} />);
expect(e.getAttribute('width')).toBe('30');
});
itRenders('simple strings', async render => {
const e = await render(<div width={'30'} />);
expect(e.getAttribute('width')).toBe('30');
});
itRenders('no string prop with true value', async render => {
const e = await render(<a href={true} />, 1);
expect(e.hasAttribute('href')).toBe(false);
});
itRenders('no string prop with false value', async render => {
const e = await render(<a href={false} />, 1);
expect(e.hasAttribute('href')).toBe(false);
});
itRenders('no string prop with null value', async render => {
const e = await render(<div width={null} />);
expect(e.hasAttribute('width')).toBe(false);
});
});
describe('boolean properties', function() {
itRenders('boolean prop with true value', async render => {
const e = await render(<div hidden={true} />);
expect(e.getAttribute('hidden')).toBe('');
});
itRenders('boolean prop with false value', async render => {
const e = await render(<div hidden={false} />);
expect(e.getAttribute('hidden')).toBe(null);
});
itRenders('boolean prop with self value', async render => {
const e = await render(<div hidden="hidden" />);
expect(e.getAttribute('hidden')).toBe('');
});
// this does not seem like correct behavior, since hidden="" in HTML indicates
// that the boolean property is present. however, it is how the current code
// behaves, so the test is included here.
itRenders('boolean prop with "" value', async render => {
const e = await render(<div hidden="" />);
expect(e.getAttribute('hidden')).toBe(null);
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with string value', async render => {
const e = await render(<div hidden="foo" />);
expect(e.getAttribute('hidden')).toBe('');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with array value', async render => {
const e = await render(<div hidden={['foo', 'bar']} />);
expect(e.getAttribute('hidden')).toBe('');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with object value', async render => {
const e = await render(<div hidden={{foo: 'bar'}} />);
expect(e.getAttribute('hidden')).toBe('');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with non-zero number value', async render => {
const e = await render(<div hidden={10} />);
expect(e.getAttribute('hidden')).toBe('');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with zero value', async render => {
const e = await render(<div hidden={0} />);
expect(e.getAttribute('hidden')).toBe(null);
});
itRenders('no boolean prop with null value', async render => {
const e = await render(<div hidden={null} />);
expect(e.hasAttribute('hidden')).toBe(false);
});
});
describe('download property (combined boolean/string attribute)', function() {
itRenders('download prop with true value', async render => {
const e = await render(<a download={true} />);
expect(e.getAttribute('download')).toBe('');
});
itRenders('download prop with false value', async render => {
const e = await render(<a download={false} />);
expect(e.getAttribute('download')).toBe(null);
});
itRenders('download prop with string value', async render => {
const e = await render(<a download="myfile" />);
expect(e.getAttribute('download')).toBe('myfile');
});
itRenders('download prop with string "false" value', async render => {
const e = await render(<a download="false" />);
expect(e.getAttribute('download')).toBe('false');
});
itRenders('download prop with string "true" value', async render => {
const e = await render(<a download={'true'} />);
expect(e.getAttribute('download')).toBe('true');
});
itRenders('download prop with number 0 value', async render => {
const e = await render(<a download={0} />);
expect(e.getAttribute('download')).toBe('0');
});
itRenders('no download prop with null value', async render => {
const e = await render(<div download={null} />);
expect(e.hasAttribute('download')).toBe(false);
});
itRenders('no download prop with undefined value', async render => {
const e = await render(<div download={undefined} />);
expect(e.hasAttribute('download')).toBe(false);
});
});
describe('className property', function() {
itRenders('className prop with string value', async render => {
const e = await render(<div className="myClassName" />);
expect(e.getAttribute('class')).toBe('myClassName');
});
itRenders('className prop with empty string value', async render => {
const e = await render(<div className="" />);
expect(e.getAttribute('class')).toBe('');
});
itRenders('no className prop with true value', async render => {
const e = await render(<div className={true} />, 1);
expect(e.hasAttribute('class')).toBe(false);
});
itRenders('no className prop with false value', async render => {
const e = await render(<div className={false} />, 1);
expect(e.hasAttribute('class')).toBe(false);
});
itRenders('no className prop with null value', async render => {
const e = await render(<div className={null} />);
expect(e.hasAttribute('className')).toBe(false);
});
itRenders('badly cased className with a warning', async render => {
const e = await render(<div classname="test" />, 1);
expect(e.hasAttribute('class')).toBe(false);
expect(e.hasAttribute('classname')).toBe(true);
});
itRenders(
'className prop when given the alias with a warning',
async render => {
const e = await render(<div class="test" />, 1);
expect(e.className).toBe('test');
},
);
itRenders(
'className prop when given a badly cased alias',
async render => {
const e = await render(<div cLASs="test" />, 1);
expect(e.className).toBe('test');
},
);
itRenders('class for custom elements', async render => {
const e = await render(<div is="custom-element" class="test" />, 0);
expect(e.getAttribute('class')).toBe('test');
});
itRenders('className for custom elements', async render => {
const e = await render(<div is="custom-element" className="test" />, 0);
expect(e.getAttribute('className')).toBe('test');
});
});
describe('htmlFor property', function() {
itRenders('htmlFor with string value', async render => {
const e = await render(<div htmlFor="myFor" />);
expect(e.getAttribute('for')).toBe('myFor');
});
itRenders('no badly cased htmlfor', async render => {
const e = await render(<div htmlfor="myFor" />, 1);
expect(e.hasAttribute('for')).toBe(false);
expect(e.getAttribute('htmlfor')).toBe('myFor');
});
itRenders('htmlFor with an empty string', async render => {
const e = await render(<div htmlFor="" />);
expect(e.getAttribute('for')).toBe('');
});
itRenders('no htmlFor prop with true value', async render => {
const e = await render(<div htmlFor={true} />, 1);
expect(e.hasAttribute('for')).toBe(false);
});
itRenders('no htmlFor prop with false value', async render => {
const e = await render(<div htmlFor={false} />, 1);
expect(e.hasAttribute('for')).toBe(false);
});
itRenders('no htmlFor prop with null value', async render => {
const e = await render(<div htmlFor={null} />);
expect(e.hasAttribute('htmlFor')).toBe(false);
});
itRenders('htmlFor attribute on custom elements', async render => {
const e = await render(<div is="custom-element" htmlFor="test" />);
expect(e.getAttribute('htmlFor')).toBe('test');
});
itRenders('for attribute on custom elements', async render => {
const e = await render(<div is="custom-element" for="test" />);
expect(e.getAttribute('for')).toBe('test');
});
});
describe('numeric properties', function() {
itRenders(
'positive numeric property with positive value',
async render => {
const e = await render(<input size={2} />);
expect(e.getAttribute('size')).toBe('2');
},
);
itRenders(
'no positive numeric property with zero value',
async render => {
const e = await render(<input size={0} />);
expect(e.hasAttribute('size')).toBe(false);
},
);
itRenders('numeric property with zero value', async render => {
const e = await render(<ol start={0} />);
expect(e.getAttribute('start')).toBe('0');
});
});
describe('props with special meaning in React', function() {
itRenders('no ref attribute', async render => {
class RefComponent extends React.Component {
render() {
return <div ref="foo" />;
}
}
const e = await render(<RefComponent />);
expect(e.getAttribute('ref')).toBe(null);
});
itRenders('no children attribute', async render => {
const e = await render(React.createElement('div', {}, 'foo'));
expect(e.getAttribute('children')).toBe(null);
});
itRenders('no key attribute', async render => {
const e = await render(<div key="foo" />);
expect(e.getAttribute('key')).toBe(null);
});
itRenders('no dangerouslySetInnerHTML attribute', async render => {
const e = await render(
<div dangerouslySetInnerHTML={{__html: '<foo />'}} />,
);
expect(e.getAttribute('dangerouslySetInnerHTML')).toBe(null);
});
itRenders('no suppressContentEditableWarning attribute', async render => {
const e = await render(<div suppressContentEditableWarning={true} />);
expect(e.getAttribute('suppressContentEditableWarning')).toBe(null);
});
itRenders('no suppressHydrationWarning attribute', async render => {
const e = await render(<span suppressHydrationWarning={true} />);
expect(e.getAttribute('suppressHydrationWarning')).toBe(null);
});
});
describe('inline styles', function() {
itRenders('simple styles', async render => {
const e = await render(<div style={{color: 'red', width: '30px'}} />);
expect(e.style.color).toBe('red');
expect(e.style.width).toBe('30px');
});
itRenders('relevant styles with px', async render => {
const e = await render(
<div
style={{
left: 0,
margin: 16,
opacity: 0.5,
padding: '4px',
}}
/>,
);
expect(e.style.left).toBe('0px');
expect(e.style.margin).toBe('16px');
expect(e.style.opacity).toBe('0.5');
expect(e.style.padding).toBe('4px');
});
itRenders('custom properties', async render => {
const e = await render(<div style={{'--foo': 5}} />);
// This seems like an odd way computed properties are exposed in jsdom.
// In a real browser we'd read it with e.style.getPropertyValue('--foo')
expect(e.style.Foo).toBe('5');
});
itRenders('no undefined styles', async render => {
const e = await render(
<div style={{color: undefined, width: '30px'}} />,
);
expect(e.style.color).toBe('');
expect(e.style.width).toBe('30px');
});
itRenders('no null styles', async render => {
const e = await render(<div style={{color: null, width: '30px'}} />);
expect(e.style.color).toBe('');
expect(e.style.width).toBe('30px');
});
itRenders('no empty styles', async render => {
const e = await render(<div style={{color: null, width: null}} />);
expect(e.style.color).toBe('');
expect(e.style.width).toBe('');
expect(e.hasAttribute('style')).toBe(false);
});
itRenders('unitless-number rules with prefixes', async render => {
const {style} = await render(
<div
style={{
lineClamp: 10,
WebkitLineClamp: 10,
MozFlexGrow: 10,
msFlexGrow: 10,
msGridRow: 10,
msGridRowEnd: 10,
msGridRowSpan: 10,
msGridRowStart: 10,
msGridColumn: 10,
msGridColumnEnd: 10,
msGridColumnSpan: 10,
msGridColumnStart: 10,
}}
/>,
);
expect(style.lineClamp).toBe('10');
expect(style.WebkitLineClamp).toBe('10');
expect(style.MozFlexGrow).toBe('10');
// jsdom is inconsistent in the style property name
// it uses on the client and when processing server markup.
// But it should be there either way.
expect(style.MsFlexGrow || style.msFlexGrow).toBe('10');
expect(style.MsGridRow || style.msGridRow).toBe('10');
expect(style.MsGridRowEnd || style.msGridRowEnd).toBe('10');
expect(style.MsGridRowSpan || style.msGridRowSpan).toBe('10');
expect(style.MsGridRowStart || style.msGridRowStart).toBe('10');
expect(style.MsGridColumn || style.msGridColumn).toBe('10');
expect(style.MsGridColumnEnd || style.msGridColumnEnd).toBe('10');
expect(style.MsGridColumnSpan || style.msGridColumnSpan).toBe('10');
expect(style.MsGridColumnStart || style.msGridColumnStart).toBe('10');
});
});
describe('aria attributes', function() {
itRenders('simple strings', async render => {
const e = await render(<div aria-label="hello" />);
expect(e.getAttribute('aria-label')).toBe('hello');
});
// this probably is just masking programmer error, but it is existing behavior.
itRenders('aria string prop with false value', async render => {
const e = await render(<div aria-label={false} />);
expect(e.getAttribute('aria-label')).toBe('false');
});
itRenders('no aria prop with null value', async render => {
const e = await render(<div aria-label={null} />);
expect(e.hasAttribute('aria-label')).toBe(false);
});
itRenders('"aria" attribute with a warning', async render => {
// Reserved for future use.
const e = await render(<div aria="hello" />, 1);
expect(e.getAttribute('aria')).toBe('hello');
});
});
describe('cased attributes', function() {
itRenders(
'badly cased aliased HTML attribute with a warning',
async render => {
const e = await render(<meta httpequiv="refresh" />, 1);
expect(e.hasAttribute('http-equiv')).toBe(false);
expect(e.getAttribute('httpequiv')).toBe('refresh');
},
);
itRenders('badly cased SVG attribute with a warning', async render => {
const e = await render(<text textlength="10" />, 1);
expect(e.getAttribute('textLength')).toBe('10');
});
itRenders('no badly cased aliased SVG attribute alias', async render => {
const e = await render(<text strokedasharray="10 10" />, 1);
expect(e.hasAttribute('stroke-dasharray')).toBe(false);
expect(e.getAttribute('strokedasharray')).toBe('10 10');
});
itRenders(
'no badly cased original SVG attribute that is aliased',
async render => {
const e = await render(<text stroke-dasharray="10 10" />, 1);
expect(e.getAttribute('stroke-dasharray')).toBe('10 10');
},
);
});
describe('unknown attributes', function() {
itRenders('unknown attributes', async render => {
const e = await render(<div foo="bar" />);
expect(e.getAttribute('foo')).toBe('bar');
});
itRenders('unknown data- attributes', async render => {
const e = await render(<div data-foo="bar" />);
expect(e.getAttribute('data-foo')).toBe('bar');
});
itRenders('badly cased reserved attributes', async render => {
const e = await render(<div CHILDREN="5" />, 1);
expect(e.getAttribute('CHILDREN')).toBe('5');
});
itRenders('"data" attribute', async render => {
// For `<object />` acts as `src`.
const e = await render(<object data="hello" />);
expect(e.getAttribute('data')).toBe('hello');
});
itRenders('no unknown data- attributes with null value', async render => {
const e = await render(<div data-foo={null} />);
expect(e.hasAttribute('data-foo')).toBe(false);
});
itRenders('unknown data- attributes with casing', async render => {
const e = await render(<div data-fooBar="true" />, 1);
expect(e.getAttribute('data-foobar')).toBe('true');
});
itRenders('unknown data- attributes with boolean true', async render => {
const e = await render(<div data-foobar={true} />);
expect(e.getAttribute('data-foobar')).toBe('true');
});
itRenders('unknown data- attributes with boolean false', async render => {
const e = await render(<div data-foobar={false} />);
expect(e.getAttribute('data-foobar')).toBe('false');
});
itRenders(
'no unknown data- attributes with casing and null value',
async render => {
const e = await render(<div data-fooBar={null} />, 1);
expect(e.hasAttribute('data-foobar')).toBe(false);
},
);
itRenders('custom attributes for non-standard elements', async render => {
const e = await render(<nonstandard foo="bar" />);
expect(e.getAttribute('foo')).toBe('bar');
});
itRenders('unknown attributes for custom elements', async render => {
const e = await render(<custom-element foo="bar" />);
expect(e.getAttribute('foo')).toBe('bar');
});
itRenders(
'no unknown attributes for custom elements with null value',
async render => {
const e = await render(<custom-element foo={null} />);
expect(e.hasAttribute('foo')).toBe(false);
},
);
itRenders(
'unknown attributes for custom elements using is',
async render => {
const e = await render(<div is="custom-element" foo="bar" />);
expect(e.getAttribute('foo')).toBe('bar');
},
);
itRenders(
'no unknown attributes for custom elements using is with null value',
async render => {
const e = await render(<div is="custom-element" foo={null} />);
expect(e.hasAttribute('foo')).toBe(false);
},
);
itRenders('SVG tags with dashes in them', async render => {
const e = await render(<svg><font-face accentHeight={10} /></svg>);
expect(e.firstChild.hasAttribute('accentHeight')).toBe(false);
expect(e.firstChild.getAttribute('accent-height')).toBe('10');
});
itRenders('cased custom attributes', async render => {
const e = await render(<div fooBar="test" />, 1);
expect(e.getAttribute('foobar')).toBe('test');
});
});
itRenders('no HTML events', async render => {
const e = await render(<div onClick={() => {}} />);
expect(e.getAttribute('onClick')).toBe(null);
expect(e.getAttribute('onClick')).toBe(null);
expect(e.getAttribute('click')).toBe(null);
});
itRenders('no unknown events', async render => {
const e = await render(
<div onunknownevent="alert("hack")" />,
1,
);
expect(e.getAttribute('onunknownevent')).toBe(null);
});
itRenders('custom attribute named `on`', async render => {
const e = await render(<div on="tap:do-something" />);
expect(e.getAttribute('on')).toEqual('tap:do-something');
});
});