/
index.js
1453 lines (1335 loc) · 46 KB
/
index.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
/*global DOMParser*/
const matchesSelector = require('./matchesSelector');
function getJSDOM() {
try {
return require('' + 'jsdom');
} catch (err) {
throw new Error(
'unexpected-dom: Running outside a browser (or in a browser without DOMParser), but could not find the `jsdom` module. Please npm install jsdom to make this work.'
);
}
}
function getHtmlDocument(str) {
if (typeof DOMParser !== 'undefined') {
return new DOMParser().parseFromString(str, 'text/html');
} else if (
typeof document !== 'undefined' &&
document.implementation &&
document.implementation.createHTMLDocument
) {
const htmlDocument = document.implementation.createHTMLDocument('');
htmlDocument.open();
htmlDocument.write(str);
htmlDocument.close();
return htmlDocument;
} else {
const jsdom = getJSDOM();
return jsdom.JSDOM
? new jsdom.JSDOM(str).window.document
: jsdom.jsdom(str);
}
}
function parseHtml(str, isFragment) {
if (isFragment) {
str = `<html><head></head><body>${str}</body></html>`;
}
const htmlDocument = getHtmlDocument(str);
if (isFragment) {
const body = htmlDocument.body;
const documentFragment = htmlDocument.createDocumentFragment();
if (body) {
for (let i = 0; i < body.childNodes.length; i += 1) {
documentFragment.appendChild(body.childNodes[i].cloneNode(true));
}
}
return documentFragment;
} else {
return htmlDocument;
}
}
function parseXml(str) {
if (typeof DOMParser !== 'undefined') {
return new DOMParser().parseFromString(str, 'text/xml');
} else {
const jsdom = getJSDOM();
if (jsdom.JSDOM) {
return new jsdom.JSDOM(str, { contentType: 'text/xml' }).window.document;
} else {
return jsdom.jsdom(str, { parsingMode: 'xml' });
}
}
}
// From html-minifier
const enumeratedAttributeValues = {
draggable: ['true', 'false'] // defaults to 'auto'
};
const matchSimpleAttribute = /^(?:allowfullscreen|async|autofocus|autoplay|checked|compact|controls|declare|default|defaultchecked|defaultmuted|defaultselected|defer|disabled|enabled|formnovalidate|hidden|indeterminate|inert|ismap|itemscope|loop|multiple|muted|nohref|noresize|noshade|novalidate|nowrap|open|pauseonexit|readonly|required|reversed|scoped|seamless|selected|sortable|spellcheck|truespeed|typemustmatch|visible)$/i;
function isBooleanAttribute(attrName) {
return matchSimpleAttribute.test(attrName);
}
function isEnumeratedAttribute(attrName) {
return attrName in enumeratedAttributeValues;
}
function validateStyles(expect, str) {
const invalidStyles = str
.split(';')
.filter(
part =>
!/^\s*(\w|-)+\s*:\s*(#(?:[0-9a-fA-F]{3}){1,2}|(\w|-)+)\s*$|^$/.test(
part
)
);
if (invalidStyles.length > 0) {
expect.errorMode = 'nested';
expect.fail(
'Expectation contains invalid styles: {0}',
invalidStyles.join(';')
);
}
}
function styleStringToObject(str) {
const styles = {};
str.split(';').forEach(rule => {
const tuple = rule.split(':').map(part => part.trim());
// Guard against empty touples
if (tuple[0] && tuple[1]) {
styles[tuple[0]] = tuple[1];
}
});
return styles;
}
function getClassNamesFromAttributeValue(attributeValue) {
if (attributeValue === null) {
return [];
}
if (attributeValue === '') {
return [];
}
const classNames = attributeValue.split(/\s+/);
if (classNames.length === 1 && classNames[0] === '') {
classNames.pop();
}
return classNames;
}
function isInsideHtmlDocument(node) {
const ownerDocument =
node.nodeType === 9 && node.documentElement && node.implementation
? node
: node.ownerDocument;
if (ownerDocument.contentType) {
return ownerDocument.contentType === 'text/html';
} else {
return ownerDocument.toString() === '[object HTMLDocument]';
}
}
function getAttributes(element) {
const isHtml = isInsideHtmlDocument(element);
const attrs = element.attributes;
const result = {};
for (let i = 0; i < attrs.length; i += 1) {
if (attrs[i].name === 'class') {
result[attrs[i].name] =
(attrs[i].value && attrs[i].value.split(' ')) || [];
} else if (attrs[i].name === 'style') {
result[attrs[i].name] = styleStringToObject(attrs[i].value);
} else {
result[attrs[i].name] =
isHtml && isBooleanAttribute(attrs[i].name)
? true
: attrs[i].value || '';
}
}
return result;
}
function getCanonicalAttributes(element) {
const attrs = getAttributes(element);
const result = {};
Object.keys(attrs)
.sort()
.forEach(key => {
result[key] = attrs[key];
});
return result;
}
function entitify(value) {
return String(value)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<');
}
function isVoidElement(elementName) {
return /(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)/i.test(
elementName
);
}
function writeAttributeToMagicPen(output, attributeName, value, isHtml) {
output.prismAttrName(attributeName);
if (!isHtml || !isBooleanAttribute(attributeName)) {
if (attributeName === 'class') {
value = value.join(' ');
} else if (attributeName === 'style') {
value = Object.keys(value)
.map(cssProp => `${cssProp}: ${value[cssProp]}`)
.join('; ');
}
output
.prismPunctuation('="')
.prismAttrValue(entitify(value))
.prismPunctuation('"');
}
}
function stringifyAttribute(attributeName, value) {
if (
isBooleanAttribute(attributeName) ||
isEnumeratedAttribute(attributeName)
) {
return attributeName;
} else if (attributeName === 'class') {
return `class="${value.join(' ')}"`; // FIXME: entitify
} else if (attributeName === 'style') {
return `style="${Object.keys(value)
// FIXME: entitify
.map(cssProp => [cssProp, value[cssProp]].join(': '))
.join('; ')}"`;
} else {
return `${attributeName}="${entitify(value)}"`;
}
}
function stringifyStartTag(element) {
const elementName =
element.ownerDocument.contentType === 'text/html'
? element.nodeName.toLowerCase()
: element.nodeName;
let str = `<${elementName}`;
const attrs = getCanonicalAttributes(element);
Object.keys(attrs).forEach(key => {
str += ` ${stringifyAttribute(key, attrs[key])}`;
});
str += '>';
return str;
}
function stringifyEndTag(element) {
const isHtml = isInsideHtmlDocument(element);
const elementName = isHtml
? element.nodeName.toLowerCase()
: element.nodeName;
if (isHtml && isVoidElement(elementName) && element.childNodes.length === 0) {
return '';
} else {
return `</${elementName}>`;
}
}
module.exports = {
name: 'unexpected-dom',
installInto(expect) {
expect = expect.child();
expect.use(require('magicpen-prism'));
function bubbleError(body) {
return expect.withError(body, err => {
err.errorMode = 'bubble';
throw err;
});
}
expect.exportType({
name: 'DOMNode',
base: 'object',
identify(obj) {
return (
obj &&
obj.nodeName &&
[2, 3, 4, 5, 6, 7, 10, 11, 12].indexOf(obj.nodeType) > -1
);
},
equal(a, b) {
return a.nodeValue === b.nodeValue;
},
inspect(element, depth, output) {
return output.code(
`${element.nodeName} "${element.nodeValue}"`,
'prism-string'
);
}
});
expect.exportType({
name: 'DOMComment',
base: 'DOMNode',
identify(obj) {
return obj && typeof obj.nodeType === 'number' && obj.nodeType === 8;
},
equal(a, b) {
return a.nodeValue === b.nodeValue;
},
inspect(element, depth, output) {
return output.code(`<!--${element.nodeValue}-->`, 'html');
},
diff(actual, expected, output, diff, inspect, equal) {
const d = diff(
`<!--${actual.nodeValue}-->`,
`<!--${expected.nodeValue}-->`
);
d.inline = true;
return d;
}
});
// Recognize <!-- ignore --> as a special subtype of DOMComment so it can be targeted by assertions:
expect.exportType({
name: 'DOMIgnoreComment',
base: 'DOMComment',
identify(obj) {
return (
this.baseType.identify(obj) && /^\s*ignore\s*$/.test(obj.nodeValue)
);
}
});
expect.exportType({
name: 'DOMTextNode',
base: 'DOMNode',
identify(obj) {
return obj && typeof obj.nodeType === 'number' && obj.nodeType === 3;
},
equal(a, b) {
return a.nodeValue === b.nodeValue;
},
inspect(element, depth, output) {
return output.code(entitify(element.nodeValue.trim()), 'html');
},
diff(actual, expected, output, diff, inspect, equal) {
const d = diff(actual.nodeValue, expected.nodeValue);
d.inline = true;
return d;
}
});
expect.exportType({
name: 'DOMNodeList',
base: 'array-like',
prefix(output) {
return output.text('NodeList[');
},
suffix(output) {
return output.text(']');
},
similar(a, b) {
// Figure out whether a and b are "struturally similar" so they can be diffed inline.
return (
a.nodeType === 1 && b.nodeType === 1 && a.nodeName === b.nodeName
);
},
identify(obj) {
return (
obj &&
typeof obj.length === 'number' &&
typeof obj.toString === 'function' &&
typeof obj.item === 'function' &&
// With jsdom 6+, nodeList.toString() comes out as '[object Object]', so fall back to the constructor name:
(obj.toString().indexOf('NodeList') !== -1 ||
(obj.constructor && obj.constructor.name === 'NodeList'))
);
}
});
// Fake type to make it possible to build 'to satisfy' diffs to be rendered inline:
expect.exportType({
name: 'attachedDOMNodeList',
base: 'DOMNodeList',
indent: false,
prefix(output) {
return output;
},
suffix(output) {
return output;
},
delimiter(output) {
return output;
},
identify(obj) {
return obj && obj._isAttachedDOMNodeList;
}
});
function makeAttachedDOMNodeList(domNodeList, contentType) {
const attachedDOMNodeList = [];
for (let i = 0; i < domNodeList.length; i += 1) {
attachedDOMNodeList.push(domNodeList[i]);
}
attachedDOMNodeList._isAttachedDOMNodeList = true;
attachedDOMNodeList.ownerDocument = { contentType };
return attachedDOMNodeList;
}
expect.exportType({
name: 'HTMLDocType',
base: 'DOMNode',
identify(obj) {
return (
obj &&
typeof obj.nodeType === 'number' &&
obj.nodeType === 10 &&
'publicId' in obj
);
},
inspect(doctype, depth, output, inspect) {
return output.code(`<!DOCTYPE ${doctype.name}>`, 'html');
},
equal(a, b) {
return a.toString() === b.toString();
},
diff(actual, expected, output, diff) {
const d = diff(
`<!DOCTYPE ${actual.name}>`,
`<!DOCTYPE ${expected.name}>`
);
d.inline = true;
return d;
}
});
expect.exportType({
name: 'DOMDocument',
base: 'DOMNode',
identify(obj) {
return (
obj &&
typeof obj.nodeType === 'number' &&
obj.nodeType === 9 &&
obj.documentElement &&
obj.implementation
);
},
inspect(document, depth, output, inspect) {
for (let i = 0; i < document.childNodes.length; i += 1) {
output.append(inspect(document.childNodes[i]));
}
return output;
},
diff(actual, expected, output, diff, inspect, equal) {
output.inline = true;
output.append(
diff(
makeAttachedDOMNodeList(actual.childNodes),
makeAttachedDOMNodeList(expected.childNodes)
)
);
return output;
}
});
expect.exportType({
name: 'HTMLDocument',
base: 'DOMDocument',
identify(obj) {
return this.baseType.identify(obj) && obj.contentType === 'text/html';
}
});
expect.exportType({
name: 'XMLDocument',
base: 'DOMDocument',
identify(obj) {
return (
this.baseType.identify(obj) &&
/^(?:application|text)\/xml|\+xml\b/.test(obj.contentType)
);
},
inspect(document, depth, output, inspect) {
output.code('<?xml version="1.0"?>', 'xml');
for (let i = 0; i < document.childNodes.length; i += 1) {
output.append(inspect(document.childNodes[i], depth - 1));
}
return output;
}
});
expect.exportType({
name: 'DOMDocumentFragment',
base: 'DOMNode',
identify(obj) {
return obj && obj.nodeType === 11; // In jsdom, documentFragment.toString() does not return [object DocumentFragment]
},
inspect(documentFragment, depth, output, inspect) {
return output
.text('DocumentFragment[')
.append(inspect(documentFragment.childNodes, depth))
.text(']');
},
diff(actual, expected, output, diff, inspect, equal) {
output.inline = true;
output.block(
diff(
makeAttachedDOMNodeList(actual.childNodes),
makeAttachedDOMNodeList(expected.childNodes)
)
);
return output;
}
});
expect.exportType({
name: 'DOMElement',
base: 'DOMNode',
identify(obj) {
return (
obj &&
typeof obj.nodeType === 'number' &&
obj.nodeType === 1 &&
obj.nodeName &&
obj.attributes
);
},
equal(a, b, equal) {
const aIsHtml = isInsideHtmlDocument(a);
const bIsHtml = isInsideHtmlDocument(b);
return (
aIsHtml === bIsHtml &&
(aIsHtml
? a.nodeName.toLowerCase() === b.nodeName.toLowerCase()
: a.nodeName === b.nodeName) &&
equal(getAttributes(a), getAttributes(b)) &&
equal(a.childNodes, b.childNodes)
);
},
inspect(element, depth, output, inspect) {
const elementName = element.nodeName.toLowerCase();
const startTag = stringifyStartTag(element);
output.code(startTag, 'html');
if (element.childNodes.length > 0) {
if (depth === 1) {
output.text('...');
} else {
const inspectedChildren = [];
if (elementName === 'script') {
let type = element.getAttribute('type');
if (!type || /javascript/.test(type)) {
type = 'javascript';
}
inspectedChildren.push(
output.clone().code(element.textContent, type)
);
} else if (elementName === 'style') {
inspectedChildren.push(
output
.clone()
.code(
element.textContent,
element.getAttribute('type') || 'text/css'
)
);
} else {
for (let i = 0; i < element.childNodes.length; i += 1) {
inspectedChildren.push(inspect(element.childNodes[i]));
}
}
let width = startTag.length;
const multipleLines = inspectedChildren.some(o => {
const size = o.size();
width += size.width;
return width > 60 || o.height > 1;
});
if (multipleLines) {
output.nl().indentLines();
inspectedChildren.forEach((inspectedChild, index) => {
output
.i()
.block(inspectedChild)
.nl();
});
output.outdentLines();
} else {
inspectedChildren.forEach((inspectedChild, index) =>
output.append(inspectedChild)
);
}
}
}
output.code(stringifyEndTag(element), 'html');
return output;
},
diffLimit: 512,
diff(actual, expected, output, diff, inspect, equal) {
const isHtml = isInsideHtmlDocument(actual);
output.inline = true;
if (Math.max(actual.length, expected.length) > this.diffLimit) {
output.jsComment(`Diff suppressed due to size > ${this.diffLimit}`);
return output;
}
const emptyElements =
actual.childNodes.length === 0 && expected.childNodes.length === 0;
const conflictingElement =
actual.nodeName.toLowerCase() !== expected.nodeName.toLowerCase() ||
!equal(getAttributes(actual), getAttributes(expected));
if (conflictingElement) {
let canContinueLine = true;
output.prismPunctuation('<').prismTag(actual.nodeName.toLowerCase());
if (
actual.nodeName.toLowerCase() !== expected.nodeName.toLowerCase()
) {
output
.sp()
.annotationBlock(output =>
output
.error('should be')
.sp()
.prismTag(expected.nodeName.toLowerCase())
)
.nl();
canContinueLine = false;
}
const actualAttributes = getAttributes(actual);
const expectedAttributes = getAttributes(expected);
Object.keys(actualAttributes).forEach(attributeName => {
output.sp(canContinueLine ? 1 : 2 + actual.nodeName.length);
writeAttributeToMagicPen(
output,
attributeName,
actualAttributes[attributeName],
isHtml
);
if (attributeName in expectedAttributes) {
if (
actualAttributes[attributeName] ===
expectedAttributes[attributeName]
) {
canContinueLine = true;
} else {
output
.sp()
.annotationBlock(output =>
output
.error('should equal')
.sp()
.append(
inspect(entitify(expectedAttributes[attributeName]))
)
)
.nl();
canContinueLine = false;
}
delete expectedAttributes[attributeName];
} else {
output
.sp()
.annotationBlock(output => output.error('should be removed'))
.nl();
canContinueLine = false;
}
});
Object.keys(expectedAttributes).forEach(attributeName => {
output.sp(canContinueLine ? 1 : 2 + actual.nodeName.length);
output
.annotationBlock(output => {
output.error('missing').sp();
writeAttributeToMagicPen(
output,
attributeName,
expectedAttributes[attributeName],
isHtml
);
})
.nl();
canContinueLine = false;
});
output.prismPunctuation('>');
} else {
output.code(stringifyStartTag(actual), 'html');
}
if (!emptyElements) {
output
.nl()
.indentLines()
.i()
.block(
diff(
makeAttachedDOMNodeList(actual.childNodes),
makeAttachedDOMNodeList(expected.childNodes)
)
)
.nl()
.outdentLines();
}
output.code(stringifyEndTag(actual), 'html');
return output;
}
});
expect.exportAssertion(
'<DOMElement> to have (class|classes) <array|string>',
(expect, subject, value) =>
expect(subject, 'to have attributes', { class: value })
);
expect.exportAssertion(
'<DOMElement> to only have (class|classes) <array|string>',
(expect, subject, value) =>
expect(subject, 'to have attributes', {
class: expect.it(className => {
const actualClasses = getClassNamesFromAttributeValue(className);
if (typeof value === 'string') {
value = getClassNamesFromAttributeValue(value);
}
return bubbleError(() =>
expect(actualClasses.sort(), 'to equal', value.sort())
);
})
})
);
expect.exportAssertion(
'<DOMTextNode> to [exhaustively] satisfy <DOMTextNode>',
(expect, subject, value) =>
expect(subject.nodeValue, 'to equal', value.nodeValue)
);
expect.exportAssertion(
'<DOMComment> to [exhaustively] satisfy <DOMComment>',
(expect, subject, value) =>
expect(subject.nodeValue, 'to equal', value.nodeValue)
);
// Avoid rendering a huge object diff when a text node is matched against a different node type:
expect.exportAssertion(
'<DOMTextNode> to [exhaustively] satisfy <object>',
(expect, subject, value) => expect.fail()
);
// Always passes:
expect.exportAssertion(
// Name each subject type to increase the specificity of the assertion
'<DOMComment|DOMElement|DOMTextNode|DOMDocument|HTMLDocType> to [exhaustively] satisfy <DOMIgnoreComment>',
(expect, subject, value) => {}
);
// Necessary because this case would otherwise be handled by the above catch-all for <object>:
expect.exportAssertion(
'<DOMTextNode> to [exhaustively] satisfy <regexp>',
(expect, { nodeValue }, value) => expect(nodeValue, 'to satisfy', value)
);
expect.exportAssertion(
'<DOMTextNode> to [exhaustively] satisfy <any>',
(expect, { nodeValue }, value) => expect(nodeValue, 'to satisfy', value)
);
function convertDOMNodeToSatisfySpec(node, isHtml) {
if (node.nodeType === 10) {
// HTMLDocType
return { name: node.nodeName };
} else if (node.nodeType === 1) {
// DOMElement
const name = isHtml ? node.nodeName.toLowerCase() : node.nodeName;
const result = { name };
if (node.attributes) {
result.attributes = {};
for (let i = 0; i < node.attributes.length; i += 1) {
result.attributes[node.attributes[i].name] =
isHtml && isBooleanAttribute(node.attributes[i].name)
? true
: node.attributes[i].value || '';
}
}
result.children = Array.prototype.map.call(node.childNodes, childNode =>
convertDOMNodeToSatisfySpec(childNode, isHtml)
);
return result;
} else if (node.nodeType === 3) {
// DOMTextNode
return node.nodeValue;
} else if (node.nodeType === 8) {
// DOMComment
return node;
} else {
throw new Error(
`to satisfy: Node type ${
node.nodeType
} is not yet supported in the value`
);
}
}
expect.exportAssertion(
'<DOMNodeList> to [exhaustively] satisfy <string>',
(expect, subject, value) => {
const isHtml = subject.ownerDocument.contentType === 'text/html';
expect.argsOutput = output =>
output.code(value, isHtml ? 'html' : 'xml');
return expect(
subject,
'to [exhaustively] satisfy',
(isHtml ? parseHtml(value, true) : parseXml(value)).childNodes
);
}
);
expect.exportAssertion(
'<DOMNodeList> to [exhaustively] satisfy <DOMNodeList>',
(expect, subject, value) => {
const isHtml = subject.ownerDocument.contentType === 'text/html';
const satisfySpecs = [];
for (let i = 0; i < value.length; i += 1) {
satisfySpecs.push(convertDOMNodeToSatisfySpec(value[i], isHtml));
}
return expect(subject, 'to [exhaustively] satisfy', satisfySpecs);
}
);
expect.exportAssertion(
'<DOMDocumentFragment> to [exhaustively] satisfy <string>',
(expect, subject, value) => {
const isHtml = isInsideHtmlDocument(subject);
expect.argsOutput = output =>
output.code(value, isHtml ? 'html' : 'xml');
return expect(
subject,
'to [exhaustively] satisfy',
isHtml ? parseHtml(value, true) : parseXml(value)
);
}
);
expect.exportAssertion(
'<DOMDocumentFragment> to [exhaustively] satisfy <DOMDocumentFragment>',
(expect, subject, { childNodes }) => {
const isHtml = subject.ownerDocument.contentType === 'text/html';
return expect(
subject,
'to [exhaustively] satisfy',
Array.prototype.map.call(childNodes, childNode =>
convertDOMNodeToSatisfySpec(childNode, isHtml)
)
);
}
);
expect.exportAssertion(
'<DOMDocumentFragment> to [exhaustively] satisfy <object|array>',
(expect, { childNodes }, value) =>
expect(childNodes, 'to [exhaustively] satisfy', value)
);
expect.exportAssertion(
'<DOMElement> to [exhaustively] satisfy <string>',
(expect, subject, value) => {
const isHtml = isInsideHtmlDocument(subject);
const documentFragment = isHtml
? parseHtml(value, true)
: parseXml(value);
if (documentFragment.childNodes.length !== 1) {
throw new Error(
'HTMLElement to satisfy string: Only a single node is supported'
);
}
expect.argsOutput = output =>
output.code(value, isHtml ? 'html' : 'xml');
return expect(
subject,
'to [exhaustively] satisfy',
documentFragment.childNodes[0]
);
}
);
expect.exportAssertion(
'<DOMDocument> to [exhaustively] satisfy <string>',
(expect, subject, value) => {
const isHtml = isInsideHtmlDocument(subject);
const valueDocument = isHtml
? parseHtml(value, false)
: parseXml(value);
return expect(
makeAttachedDOMNodeList(subject.childNodes),
'to [exhaustively] satisfy',
Array.prototype.map.call(valueDocument.childNodes, childNode =>
convertDOMNodeToSatisfySpec(childNode, isHtml)
)
);
}
);
expect.exportAssertion(
'<DOMDocument> to [exhaustively] satisfy <DOMDocument>',
(expect, subject, { childNodes }) => {
const isHtml = isInsideHtmlDocument(subject);
return expect(
makeAttachedDOMNodeList(subject.childNodes),
'to [exhaustively] satisfy',
Array.prototype.map.call(childNodes, childNode =>
convertDOMNodeToSatisfySpec(childNode, isHtml)
)
);
}
);
expect.exportAssertion(
'<DOMElement> to [exhaustively] satisfy <DOMElement>',
(expect, subject, value) =>
expect(
subject,
'to [exhaustively] satisfy',
convertDOMNodeToSatisfySpec(value, isInsideHtmlDocument(subject))
)
);
expect.exportAssertion(
[
'<DOMElement> to [exhaustively] satisfy <DOMTextNode>',
'<DOMTextNode> to [exhaustively] satisfy <DOMElement>',
'<DOMElement|DOMDocumentFragment|DOMDocument> to [exhaustively] satisfy <regexp>'
],
(expect, subject, value) => expect.fail()
);
expect.exportAssertion(
'<DOMElement> to [exhaustively] satisfy <object>',
(expect, subject, value) => {
const isHtml = isInsideHtmlDocument(subject);
const unsupportedOptions = Object.keys(value).filter(
key =>
key !== 'attributes' &&
key !== 'name' &&
key !== 'children' &&
key !== 'onlyAttributes' &&
key !== 'textContent'
);
if (unsupportedOptions.length > 0) {
throw new Error(
`Unsupported option${
unsupportedOptions.length === 1 ? '' : 's'
}: ${unsupportedOptions.join(', ')}`
);
}
const promiseByKey = {
name: expect.promise(() => {
if (value && typeof value.name !== 'undefined') {
return bubbleError(() =>
expect(
isHtml ? subject.nodeName.toLowerCase() : subject.nodeName,
'to satisfy',
value.name
)
);
}
}),
children: expect.promise(() => {
if (typeof value.children !== 'undefined') {
if (typeof value.textContent !== 'undefined') {
throw new Error(
'The children and textContent properties are not supported together'
);
}
return bubbleError(() =>
expect(
makeAttachedDOMNodeList(
subject.childNodes,
subject.ownerDocument.contentType
),
'to satisfy',
value.children
)
);
} else if (typeof value.textContent !== 'undefined') {
return bubbleError(() =>
expect(subject.textContent, 'to satisfy', value.textContent)
);
}
}),
attributes: {}
};
const onlyAttributes =
(value && value.onlyAttributes) || expect.flags.exhaustively;
const attrs = getAttributes(subject);
let expectedAttributes = value && value.attributes;