Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1642 lines (1418 loc) · 61.3 KB
/
Copy pathindex.js
File metadata and controls
1642 lines (1418 loc) · 61.3 KB
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
var path = require("path");
var fs = require("fs");
var jsdom = require('../../lib/jsdom');
var inheritFrom = require("../../lib/jsdom/utils").inheritFrom;
var toFileUrl = require('../util').toFileUrl(__dirname);
var http = require("http");
var URL = require('url');
var um = require('urlmaster');
var serializeDocument = require('../../lib/jsdom').serializeDocument;
function tmpWindow() {
return jsdom.jsdom().defaultView;
}
function testFunction(test, window, jQuery, checkVersion) {
test.notEqual(window.jQuery.find, null, 'window.jQuery.find should not be null');
test.notEqual(jQuery.find, null, 'jQuery.find should not be null');
jQuery("body").html('<p id="para"><a class="link">click <em class="emph">ME</em></a></p>');
var res = jQuery("#para .emph").text();
var res2 = jQuery("a.link .emph").text();
test.equal(jQuery('p#para a.link', window.document.body).attr('class'), 'link', "selecting from body");
if (checkVersion) {
test.strictEqual(jQuery('body').jquery, '1.4.4', 'jQuery version 1.4.4');
}
test.equal(res, "ME", "selector should work as expected");
test.equal(res2, "ME", "selector should work as expected");
};
exports.tests = {
build_window: function(test) {
var window = jsdom.jsdom().defaultView;
test.notEqual(window, null, 'window should not be null');
test.notEqual(window.document, null, 'window.document should not be null');
test.done();
},
jsdom_takes_html: function(test) {
var document = jsdom.jsdom('<a id="test" href="#test">');
test.equal(document.getElementById("test").getAttribute("href"), '#test', 'Passing html into jsdom() should populate the resulting doc');
test.done();
},
jsdom_empty_html: function(test) {
var emptyDoc = jsdom.jsdom('');
var blankDoc = jsdom.jsdom(' ');
test.equal(emptyDoc.innerHTML, blankDoc.innerHTML, 'Passing blank and empty strings into jsdom() result in the same html');
test.done();
},
jsdom_method_creates_default_document: function(test) {
var doc = jsdom.jsdom();
test.equal(doc.documentElement.nodeName, 'HTML', 'Calling jsdom.jsdom() should automatically populate the doc');
test.done();
},
jquerify_file: function(test) {
var jQueryFile = path.resolve(__dirname, '../jquery-fixtures/jquery-1.4.4.js');
test.expect(6);
jsdom.jQueryify(tmpWindow(), jQueryFile, function(window, jQuery) {
testFunction(test, window, jQuery, true);
test.done();
});
},
jquerify_url: function(test) {
var jQueryUrl = 'http://code.jquery.com/jquery-1.4.4.min.js';
test.expect(6);
jsdom.jQueryify(tmpWindow(), jQueryUrl, function (window, jQuery) {
testFunction(test, window, jQuery, true);
test.done();
});
},
jquerify_invalid: function (test) {
test.expect(2);
jsdom.jQueryify(tmpWindow(), 1, function (window, jQuery) {
test.strictEqual(window.jQuery, undefined);
test.strictEqual(jQuery, undefined);
test.done();
});
},
jquerify_attribute_selector_gh_400: function(test) {
var window = jsdom.jsdom().defaultView;
jsdom.jQueryify(window, path.resolve(__dirname, '../jquery-fixtures/jquery-1.11.0.js'), function () {
try {
window.$("body").append('<html><body><div data-foo="bar"/><div data-baz="foo"/></body></html>');
test.equal(window.$('*[data-foo]').length, 1);
test.done();
}
catch(ex) {
console.log(ex);
test.ok(false, "Encountered an error");
test.done();
}
});
},
// This is in response to issue # 280 - scripts don't load over https.
// See: https://github.com/tmpvar/jsdom/issues/280
//
// When a transfer is done, HTTPS servers in the wild might emit 'close', or
// might emit 'end'. Node's HTTPS server always emits 'end', so we need to
// fake a 'close' to test this fix.
env_with_https : function (test) {
var https = require('https');
// Save the real https.request so we can restore it later.
var oldRequest = https.request;
var EventEmitter = require('events').EventEmitter;
// Mock response object
var res = Object.create(EventEmitter.prototype);
res.headers = {};
// Monkey patch https.request so it emits 'close' instead of 'end.
https.request = function () {
// Mock the request object.
var req = Object.create(EventEmitter.prototype);
req.setHeader = function () {};
req.end = function () {};
process.nextTick(function () {
req.emit('response', res);
process.nextTick(function () {
res.emit('data', 'window.attachedHere = 123');
res.emit('close');
});
});
return req;
};
jsdom.env({
html: "<a href='/path/to/hello'>World</a>",
// The script url doesn't matter as long as its https, since our mocked
// request doens't actually fetch anything.
scripts: 'https://doesntmatter.com/script.js',
done: function(errors, window) {
if (errors) {
test.ok(false, errors.message);
} else {
test.notEqual(window.location, null, 'window.location should not be null');
test.equal(window.attachedHere, 123, 'script should execute on our window');
test.equal(window.document.getElementsByTagName("a").item(0).innerHTML, 'World', 'anchor text');
}
https.request = oldRequest;
test.done();
}
});
},
env_with_compression : function (test) {
var zlib = require('zlib');
var server = http.createServer(function (req, res) {
switch (req.url) {
case "/":
var text = 'window.attachedHere = 123';
var buf = new Buffer(text, 'utf-8');
zlib.gzip(buf, function (_, result) {
res.writeHead(200, { "Content-Length": result.length, 'Content-Encoding':'gzip' });
res.emit('data', result);
res.end(result);
});
break;
}
});
server.listen(8001, "127.0.0.1", function () {
jsdom.env({
html: "<a href='/path/to/hello'>World</a>",
scripts: 'http://127.0.0.1:8001',
done: function(errors, window) {
server.close();
if (errors) {
test.ok(false, errors.message);
} else {
test.notEqual(window.location, null, 'window.location should not be null');
test.equal(window.attachedHere, 123, 'script should execute on our window');
test.equal(window.document.getElementsByTagName("a").item(0).innerHTML, 'World', 'anchor text');
}
test.done();
}
});
});
},
env_with_features_and_external_resources: function(test) {
jsdom.env(
'http://documentcloud.github.com/backbone/examples/todos/index.html',
{
features: {
FetchExternalResources : ['script', 'img', 'css', 'frame', 'link'],
ProcessExternalResources : ['script', 'img', 'css', 'frame', 'link'],
MutationEvents : '2.0',
QuerySelector : false
}
},
function(errors, window) {
test.notEqual(errors, null, 'localStorage error should occur');
test.equal(typeof window._, 'function', 'Underscore loaded');
test.equal(typeof window.$, 'function', 'jQuery loaded');
test.done();
}
);
},
appendChild_to_document_with_existing_documentElement: function(test) {
test.expect(2);
t = function(){
try {
var doc = jsdom.jsdom();
doc.appendChild(doc.createElement('html'));
} catch (e) {
test.equal(e.code, 3, 'Should throw HIERARCHY_ERR');
code = e.code;
throw(e);
}
};
test.throws(t);
test.done();
},
ensure_scripts_can_be_disabled_via_options_features: function(test) {
var html = '<html><head><script src="./files/hello.js"></script></head>' +
'<body><span id="test">hello from html</span></body></html>';
var doc2 = jsdom.jsdom(html, {
url: toFileUrl(__filename),
features: {
FetchExternalResources: ['script'],
ProcessExternalResources: false
}
});
setTimeout(function() {
test.equal(doc2.getElementById("test").innerHTML, 'hello from html', 'js should not be executed (doc2)');
test.done();
}, 100);
},
ensure_scripts_can_be_executed_via_options_features: function (t) {
var html = "<html><head><script src='./files/hello.js'></script></head>" +
"<body><span id='test'>hello from html</span></body></html>";
var doc = jsdom.jsdom(html, {
url: toFileUrl(__filename),
features: {
FetchExternalResources: ["script"],
ProcessExternalResources: ["script"]
}
});
doc.defaultView.doCheck = function () {
t.equal(doc.getElementById("test").innerHTML, "hello from javascript");
t.done();
};
},
ensure_resolution_is_not_thrown_off_by_hrefless_base_tag: function (t) {
var html = "<html><head><base target='whatever'>" +
"<script src='./files/hello.js'></script></head><body>" +
"<span id='test'>hello from html</span></body></html>";
var doc = jsdom.jsdom(html, {
url: toFileUrl(__filename),
features: {
FetchExternalResources: ["script"],
ProcessExternalResources: ["script"]
}
});
doc.defaultView.doCheck = function () {
t.equal(doc.getElementById("test").innerHTML, "hello from javascript");
t.done();
};
},
ensure_resources_can_be_skipped_via_options_features: function(test) {
var html = '<html><head><script src="./files/hello.js"></script>' +
'<script src="./files/nyan.js"></script></head>' +
'<body><span id="test">hello from html</span><span id="cat">' +
'hello from cat</body></html>';
var doc2 = jsdom.jsdom(html, {
url: toFileUrl(__filename),
features: {
FetchExternalResources: ['script'],
ProcessExternalResources: ['script'],
SkipExternalResources: new RegExp('.*/files/h')
}
});
doc2.defaultView. () {
test.equal(doc2.getElementById("test").innerHTML, 'hello from html', 'js should not be executed (doc2)');
test.equal(doc2.getElementById("cat").innerHTML, 'hello from nyan cat', 'js should be executed (doc2)');
test.done();
};
},
load_multiple_resources_with_defer_close: function(test) {
var html = '<html><head></head><frameset>' +
'<frame src="../level2/html/files/iframe.html"></frame>' +
'<frame src="../level2/html/files/iframe.html"></frame>' +
'<frame src="../level2/html/files/iframe.html"></frame>' +
'</frameset></html>';
var doc = jsdom.jsdom(html,
{
url: toFileUrl(__filename),
features: {
FetchExternalResources: ['frame'],
ProcessExternalResources: ['frame','script']
},
deferClose: true
});
// iframe.html sets onload handler to call loadComplete, so we mock it.
var window = doc.defaultView;
doc.parent = window;
window.loadComplete = function () {};
test.ok(doc._queue.paused, 'resource queue should be paused');
var check_handle;
var timeout_handle = setTimeout(function() {
doc.>
doc.defaultView.close();
if (check_handle) {
clearTimeout(check_handle);
}
test.ok(false, "timed out when waiting for onload to fire");
test.done();
}, 1000); //1 second timeout
function check() {
var q = doc._queue, h = q.tail, count=0;
check_handle = null;
while (h) {
if (h.fired) {
count++;
h = h.prev;
} else {
check_handle = setTimeout(check, 50);
return;
}
}
test.equal(count, 3, 'there should be 3 resources in the resource queue');
doc.close();
}
check_handle = setTimeout(check, 50);
doc. {
clearTimeout(timeout_handle);
test.done();
};
},
resource_queue: function(test) {
//ResourceQueue is not exported, so grab it from a doc
var doc = jsdom.jsdom(), q = doc._queue, counter = 0, increment=function() {counter++;};
var queueHandles = [q.push(increment), q.push(increment)];
queueHandles[0](null, true);
queueHandles.push(q.push(increment));
queueHandles[1](null, true);
queueHandles[2](null, true);
test.strictEqual(counter, 3);
test.strictEqual(q.tail, null);
test.done();
},
understand_file_protocol: function(test) {
var html = '\
<html>\
<head>\
<script type="text/javascript" src="' + toFileUrl('files/hello.js') + '"></script>\
</head>\
<body>\
<span id="test">hello from html</span>\
</body>\
</html>';
var doc = jsdom.jsdom(html);
doc. {
test.equal(doc.getElementById("test").innerHTML, 'hello from javascript', 'resource with file protocol should work');
test.done();
};
},
importNode: function(test) {
test.doesNotThrow(function() {
var doc1 = jsdom.jsdom('<html><body><h1 id="headline">Hello <span id="world">World</span></h1></body></html>'),
doc2 = jsdom.jsdom();
doc2.body.appendChild(doc2.importNode(doc1.getElementById('headline'), true));
doc2.getElementById('world').className = 'foo';
});
test.done();
},
window_is_augmented_with_dom_features: function(test) {
var document = jsdom.jsdom(),
window = document.defaultView;
test.notEqual(window.Element, null, 'window.Element should not be null');
test.done();
},
queryselector: function(test) {
var html = '<html><body><div id="main"><p class="foo">Foo</p><p>Bar</p></div></body></html>',
document = jsdom.jsdom(html),
div = document.body.children.item(0);
var element = document.querySelector("#main p");
test.equal(element, div.children.item(0), 'p and first-p');
var element2 = div.querySelector("p");
test.equal(element2, div.children.item(0), 'p and first-p');
var element3 = document.querySelector("#main p:not(.foo)");
test.equal(element3, div.children.item(1), 'p and second-p');
var element3 = document.querySelector("#asdf");
test.strictEqual(element3, null, 'nonexistent becomes null');
test.done();
},
queryselector_documentfragment: function(test) {
var html = '<html><body><div id="main"><p class="foo">Foo</p><p>Bar</p></div></body></html>',
document = jsdom.jsdom(html),
div = document.body.children.item(0),
fragment = document.createDocumentFragment();
fragment.appendChild(document.body.firstChild);
test.strictEqual(document.body.firstChild, null);
var element = fragment.querySelector("#main p");
test.equal(element, div.children.item(0), 'p and first-p');
var element2 = div.querySelector("p");
test.equal(element2, div.children.item(0), 'p and first-p');
var element3 = fragment.querySelector("#main p:not(.foo)");
test.equal(element3, div.children.item(1), 'p and second-p');
var element3 = fragment.querySelector("#asdf");
test.strictEqual(element3, null, 'nonexistent becomes null');
test.done();
},
// TODO: look into breaking into a testcase
queryselectorall: function(test) {
var html = '<html><body><div id="main"><p>Foo</p><p>Bar</p></div><div id="next"><div id="next-child"><p>Baz</p></div></div></body></html>',
document = jsdom.jsdom(html),
div = document.body.children.item(0),
elements = document.querySelectorAll("#main p");
test.equal(elements.length, 2, 'two results');
test.equal(elements.item(0), div.children.item(0), 'p and first-p');
test.equal(elements.item(1), div.children.item(1), 'p and second-p');
var elements2 = div.querySelectorAll("p");
test.equal(elements2.length, 2, 'two results');
test.equal(elements2.item(0), div.children.item(0), 'p and first-p');
test.equal(elements2.item(1), div.children.item(1), 'p and second-p');
test.equal(div.querySelectorAll("#main").length, 0, 'It should not return the base element');
test.equal(div.querySelectorAll("div").length, 0, 'There are no div elements under div#main');
var elements3 = div.querySelectorAll("#main p");
test.equal(elements3.length, 2, 'two results');
test.equal(elements3.item(0), div.children.item(0), 'p and first-p');
test.equal(elements3.item(1), div.children.item(1), 'p and second-p');
var topNode = document.createElement('p'),
newNode = document.createElement('p');
topNode.id = "fuz";
newNode.id = "buz";
topNode.appendChild(newNode);
test.equal(topNode.querySelectorAll("#fuz").length, 0, "It should not return the base element that is orphaned");
var elements4 = topNode.querySelectorAll("#fuz #buz");
test.equal(elements4.length, 1, 'one result');
test.equal(elements4.item(0), newNode, 'newNode and first-p');
var elements5 = div.querySelectorAll('p');
test.equal(elements5.length, 2, "It should not return elements that are not within the base element's subtrees");
test.equal(elements5.item(0), div.children.item(0), 'p and first-p');
test.equal(elements5.item(1), div.children.item(1), 'p and second-p');
test.strictEqual(topNode.parentNode, null, 'topNode.parentNode is null');
var nextChildDiv = document.getElementById('next-child');
var elements6 = nextChildDiv.querySelectorAll('p');
test.equal(elements6.length, 1, 'p under div#next-child');
test.equal(elements6.item(0), nextChildDiv.children.item(0), 'child of div#next-child');
test.done();
},
queryselectorall__documentfragment: function(test) {
var html = '<html><body><div id="main"><p>Foo</p><p>Bar</p></div><div id="next"><div id="next-child"><p>Baz</p></div></div></body></html>',
document = jsdom.jsdom(html),
fragment = document.createDocumentFragment();
fragment.appendChild(document.body.firstChild);
fragment.appendChild(document.body.firstChild);
test.strictEqual(document.body.firstChild, null, 'The body should now be empty');
var div = fragment.firstChild;
var elements = fragment.querySelectorAll("#main p");
test.equal(elements.length, 2, 'two results');
test.equal(elements.item(0), div.children.item(0), 'p and first-p');
test.equal(elements.item(1), div.children.item(1), 'p and second-p');
var elements2 = div.querySelectorAll("p");
test.equal(elements2.length, 2, 'two results');
test.equal(elements2.item(0), div.children.item(0), 'p and first-p');
test.equal(elements2.item(1), div.children.item(1), 'p and second-p');
test.equal(div.querySelectorAll("#main").length, 0, 'It should not return the base element');
test.equal(div.querySelectorAll("div").length, 0, 'There are no div elements under div#main');
var elements3 = div.querySelectorAll("#main p");
test.equal(elements3.length, 2, 'two results');
test.equal(elements3.item(0), div.children.item(0), 'p and first-p');
test.equal(elements3.item(1), div.children.item(1), 'p and second-p');
var topNode = document.createElement('p'),
newNode = document.createElement('p');
topNode.id = "fuz";
newNode.id = "buz";
topNode.appendChild(newNode);
test.equal(topNode.querySelectorAll("#fuz").length, 0, "It should not return the base element that is orphaned");
var elements4 = topNode.querySelectorAll("#fuz #buz");
test.equal(elements4.length, 1, 'one result');
test.equal(elements4.item(0), newNode, 'newNode and first-p');
var elements5 = div.querySelectorAll('p');
test.equal(elements5.length, 2, "It should not return elements that are not within the base element's subtrees");
test.equal(elements5.item(0), div.children.item(0), 'p and first-p');
test.equal(elements5.item(1), div.children.item(1), 'p and second-p');
test.equal(topNode.parentNode, null, 'topNode.parentNode is null');
var nextChildDiv = fragment.querySelectorAll('#next-child').item(0);
test.notStrictEqual(nextChildDiv, null, 'id selector on fragment not null');
var elements6 = nextChildDiv.querySelectorAll('p');
test.equal(elements6.length, 1, 'p under div#next-child');
test.equal(elements6.item(0), nextChildDiv.children.item(0), 'child of div#next-child');
var elements7 = fragment.querySelectorAll('p');
test.equal(elements7.length, 3, 'all p');
test.equal(elements7.item(0), div.children.item(0), 'p and first-p');
test.equal(elements7.item(1), div.children.item(1), 'p and second-p');
test.equal(elements7.item(2), nextChildDiv.children.item(0), 'child of div#next-child');
test.done();
},
matches: function(test) {
var html = '<html><body><div id="main"><p class="foo">Foo</p><p>Bar</p></div></body></html>';
var document = jsdom.jsdom(html);
var div = document.body.children.item(0);
var element = document.querySelector("#main p");
test.equal(element.matches("#main p"), true, 'p and first-p');
var element2 = div.querySelector("p");
test.equal(element2.matches("p"), true, 'p and first-p');
var element3 = document.querySelector("#main p:not(.foo)");
test.equal(element3.matches("#main p:not(.foo)"), true, 'p and second-p');
test.equal(element.matches("#asdf"), false, "doesn't match wrong selector");
test.equal(element2.matches("#asdf"), false, "doesn't match wrong selector");
test.equal(element3.matches("#asdf"), false, "doesn't match wrong selector");
test.done();
},
url_resolution: function(test) {
var html = '\
<html>\
<head></head>\
<body>\
<a href="http://example.com" id="link1">link1</a>\
<a href="/local.html" id="link2">link2</a>\
<a href="local.html" id="link3">link3</a>\
<a href="../../local.html" id="link4">link4</a>\
<a href="#here" id="link5">link5</a>\
<a href="//example.com/protocol/avoidance.html" id="link6">protocol</a>\
</body>\
</html>';
function testLocal() {
var url = '/path/to/docroot/index.html';
var doc = jsdom.jsdom(html, {url: url});
test.equal(um.addPathEmpty(doc.getElementById("link1").href), 'http://example.com/', 'Absolute URL should be left alone except for possible trailing slash');
test.equal(doc.getElementById("link2").href, '/local.html', 'Relative URL should be resolved');
test.equal(doc.getElementById("link3").href, '/path/to/docroot/local.html', 'Relative URL should be resolved');
test.equal(doc.getElementById("link4").href, '/path/local.html', 'Relative URL should be resolved');
test.equal(doc.getElementById("link5").href, '/path/to/docroot/index.html#here', 'Relative URL should be resolved');
//test.equal(doc.getElementById("link6").href, '//prototol/avoidance.html', 'Protocol-less URL should be resolved');
}
function testRemote() {
var url = 'http://example.com/path/to/docroot/index.html';
var doc = jsdom.jsdom(html, {url: url});
test.equal(um.addPathEmpty(doc.getElementById("link1").href), 'http://example.com/', 'Absolute URL should be left alone except for possible trailing slash');
test.equal(doc.getElementById("link2").href, 'http://example.com/local.html', 'Relative URL should be resolved');
test.equal(doc.getElementById("link3").href, 'http://example.com/path/to/docroot/local.html', 'Relative URL should be resolved');
test.equal(doc.getElementById("link4").href, 'http://example.com/path/local.html', 'Relative URL should be resolved');
test.equal(doc.getElementById("link5").href, 'http://example.com/path/to/docroot/index.html#here', 'Relative URL should be resolved');
test.equal(doc.getElementById("link6").href, 'http://example.com/protocol/avoidance.html', 'Relative URL should be resolved');
}
function testBase() {
var url = 'blahblahblah-invalid',
doc = jsdom.jsdom(html, {url: url}),
base = doc.createElement("base");
base.href = 'http://example.com/path/to/docroot/index.html';
doc.getElementsByTagName("head").item(0).appendChild(base);
test.equal(um.addPathEmpty(doc.getElementById("link1").href), 'http://example.com/', 'Absolute URL should be left alone except for possible trailing slash');
test.equal(doc.getElementById("link2").href, 'http://example.com/local.html', 'Relative URL should be resolved');
test.equal(doc.getElementById("link3").href, 'http://example.com/path/to/docroot/local.html', 'Relative URL should be resolved');
test.equal(doc.getElementById("link4").href, 'http://example.com/path/local.html', 'Relative URL should be resolved');
test.equal(doc.getElementById("link5").href, 'http://example.com/path/to/docroot/index.html#here', 'Relative URL should be resolved');
test.equal(doc.getElementById("link6").href, 'http://example.com/protocol/avoidance.html', 'Relative URL should be resolved');
}
function testAutomated() {
// RFC resolution cases from http://tools.ietf.org/html/rfc3986#section-5.2
// urlmaster builds them all for us
// create a doc with all of the possible bases and all of the possible refs
bases = um.generateAll({ scheme: 'http', auth: 'www.why.com', path:'/a/b', query:'?foo=bar', frag:'#abc' }, true),
refs = um.generateAll({ scheme: 'https', auth: 'www.not.com', path:'/q/r', uery:'?when=now', frag:'#xyz' }, true);
// build html with every possible link
var html = '<html><head><base href=""></base></head><body>';
refs.forEach(function (ref, i) {
html += '<a href="' + ref + '" id="link' + i + '">link' + i + '</a>\n';
});
html += '</body></html>';
var locn = toFileUrl(__filename);
// now check each base case
bases.forEach(function (base, i) {
var doc = jsdom.jsdom(html, { url: locn });
var expected = um.resolveTrack(locn, base, refs);
// set up the base
doc.getElementsByTagName("base")[0].setAttribute("href",base);
refs.forEach(function (ref, j){
var href = doc.getElementById("link" + j).href;
var result = expected[j][3];
// empty path must accept href with or without a slash; see http://tools.ietf.org/html/rfc3986#section-3.3
// so we consistently push them towards having
test.equal(um.addPathEmpty(href), um.addPathEmpty(result),
'locn \'' + locn + '\' base \'' + base + '\' with ref \'' +
ref + '\' should resolve to \'' + result + '\' (' +
um.addPathEmpty(result) + ') instead of \'' + href +
'\' (' + um.addPathEmpty(href) + ')');
});
});
}
testLocal();
testRemote();
testBase();
testAutomated();
test.done();
},
numeric_values: function(test) {
var html = '<html><body><td data-year="2011" data-month="0" data-day="9">\
<a href="#" class=" ">9</a> \
</td></body></html>';
var document = jsdom.jsdom(html);
var a = document.body.children.item(0);
a.innerHTML = 9;
a.setAttribute('id', 123);
test.strictEqual(a.innerHTML, '9', 'Element stringify');
test.strictEqual(a.getAttributeNode('id').nodeValue, '123', 'Attribute stringify');
test.done();
},
auto_tostring: function(test) {
var buffer = require("fs").readFileSync(__dirname + "/files/env.html"),
dom;
test.doesNotThrow(function(){ dom = jsdom.jsdom(buffer); }, 'buffers should automatically be stringified');
test.equal(dom.documentElement.getElementsByTagName("*").length, 3, 'should parse as per usual');
test.done();
},
document_should_expose_location: function(test) {
var window = jsdom.jsdom("").defaultView;
test.strictEqual(window.document.location, window.location, 'document.location and window.location');
test.done();
},
mutation_events : function(test) {
var document = jsdom.jsdom();
document.implementation._addFeature('MutationEvents', '2.0');
var created = '';
var removed = '';
document.addEventListener('DOMNodeInserted', function(ev) {
created += ev.target.tagName;
});
document.addEventListener('DOMNodeRemoved', function(ev) {
removed += ev.target.tagName;
});
var h1 = document.createElement('h1');
var h2 = document.createElement('h2');
var h3 = document.createElement('h3');
document.body.appendChild(h2);
document.body.insertBefore(h1, h2);
document.body.insertBefore(h3, null);
test.strictEqual('H2H1H3', created, "an event should be dispatched for each created element");
document.body.removeChild(h1);
document.body.insertBefore(h3, h2);
test.strictEqual('H1H3', removed, "an event should be dispatched for each removed element");
var text = h2.innerHTML = 'foo';
h2.addEventListener('DOMCharacterDataModified', function(ev) {
text = ev.target.nodeValue;
});
h2.firstChild.nodeValue = 'bar';
test.equal(h2.innerHTML, text, 'ChactaterData changes should be captured');
var event;
h2.setAttribute('class', 'foo');
document.addEventListener('DOMAttrModified', function(ev) {
event = ev;
});
h2.setAttribute('class', 'bar');
test.ok(!!event, 'Changing an attribute should trigger DOMAttrModified');
test.equal(event.attrName, 'class', 'attrName should be class');
test.equal(event.prevValue, 'foo', 'prevValue should be foo');
test.equal(event.newValue, 'bar', 'newValue should be bar');
event = false;
h2.setAttribute('class', 'bar');
test.ok(!event, 'Setting the same value again should not trigger an event');
h2.removeAttribute('class');
test.ok(!!event, 'Removing an attribute should trigger DOMAttrModified');
test.equal(event.attrName, 'class', 'attrName should be class');
test.equal(event.prevValue, 'bar', 'prevValue should be bar');
test.done();
},
remove_listener_in_handler: function(test) {
var document = jsdom.jsdom();
var h1 = 0, h2 = 0;
// Event handler that removes itself
function handler1() {
h1++;
document.removeEventListener('click', handler1);
}
function handler2() {
h2++;
}
document.addEventListener('click', handler1);
document.addEventListener('click', handler2);
var ev = document.createEvent('MouseEvents');
ev.initEvent('click', true, true);
document.dispatchEvent(ev);
test.equal(1, h1, "handler1 must be called once");
test.equal(1, h2, "handler2 must be called once");
document.dispatchEvent(ev);
test.equal(1, h1, "handler1 must be called once");
test.equal(2, h2, "handler2 must be called twice");
test.done();
},
childNodes_updates_on_insertChild : function(test) {
var window = jsdom.jsdom("").defaultView;
var div = window.document.createElement("div");
var text = window.document.createTextNode("bar");
div.appendChild(text);
test.strictEqual(text, div.childNodes[0],
"childNodes NodeList should update after appendChild");
text = window.document.createTextNode("bar");
div.insertBefore(text, null);
test.strictEqual(text, div.childNodes[1],
"childNodes NodeList should update after insertBefore");
test.done();
},
option_set_selected : function(test) {
var window = jsdom.jsdom("").defaultView;
var select = window.document.createElement("select");
var option0 = window.document.createElement('option');
select.appendChild(option0);
option0.setAttribute('selected', 'selected');
var optgroup = window.document.createElement('optgroup');
select.appendChild(optgroup);
var option1 = window.document.createElement('option');
optgroup.appendChild(option1);
test.strictEqual(true, option0.selected, 'initially selected');
test.strictEqual(false, option1.selected, 'initially not selected');
test.strictEqual(option1, select.options[1], "options should include options inside optgroup");
option1.defaultSelected = true;
test.strictEqual(false, option0.selected, 'selecting other option should deselect this');
test.strictEqual(true, option0.defaultSelected, 'default should not change');
test.strictEqual(true, option1.selected, 'selected changes when defaultSelected changes');
test.strictEqual(true, option1.defaultSelected, 'I just set this');
option0.defaultSelected = false;
option0.selected = true;
test.strictEqual(true, option0.selected, 'I just set this');
test.strictEqual(false, option0.defaultSelected, 'selected does not set default');
test.strictEqual(false, option1.selected, 'should deselect others');
test.strictEqual(true, option1.defaultSelected, 'unchanged');
test.done();
},
case_sensitivity_of_markup_missing_html_and_body : function(test){
var spaces = /[ \n]*/g,
doc1 = serializeDocument(jsdom.jsdom("<HTML><BODY></BODY></HTML>")).replace(spaces, ''),
doc2 = serializeDocument(jsdom.jsdom("<html><BODY></Body></HTML>")).replace(spaces, ''),
doc3 = serializeDocument(jsdom.jsdom("<html><body></body></html>")).replace(spaces, ''),
doc4 = serializeDocument(jsdom.jsdom("<body></body>")).replace(spaces, ''),
doc5 = serializeDocument(jsdom.jsdom("")).replace(spaces, '');
test.ok(doc1 === doc2 && doc2 == doc3 && doc3 === doc4 && doc4 == doc5,
'they should all serialize the same');
test.done();
},
serialization_of_void_elements : function(test){
var html = '<html><head></head><body><div><br><hr><audio><source></audio></div></body></html>',
doc = jsdom.jsdom(html);
test.strictEqual(serializeDocument(doc), html)
test.done();
},
children_should_be_available_right_after_document_creation : function(test) {
var doc = jsdom.jsdom("<html><body><div></div></body></html>");
test.ok((doc.body.children[0] !== undefined), "there should be a body, and it should have a child");
test.done();
},
children_should_be_available_right_after_document_creation_scripts : function(test) {
var html = "<html><body>" +
"<script type='text/javascript'>" +
"var h = document.createElement('div');" +
"h.innerHTML = '<div style=\"opacity:0.8\"></div>';" +
"window.myNode = h.childNodes[0];" +
"</script>" +
"</body></html>";
var window = jsdom.jsdom(html).defaultView;
test.ok(!!window.myNode.nodeType);
test.done();
},
fix_for_issue_172 : function(test) {
jsdom.env("<html><body><script type='text/javascript'></script></body></html>", [
path.resolve(__dirname, '../jquery-fixtures/jquery-1.6.2.js')
], function () {
// ensure the callback gets called!
test.done();
});
},
fix_for_issue_221 : function(test) {
var html = '<html><head></head><body></body></html>';
var document = jsdom.jsdom(html);
var div = document.createElement("div");
document.body.appendChild(div);
div.appendChild(document.createTextNode("hello world"));
test.strictEqual(div.childNodes[0].nodeValue, 'hello world',
'Nodelist children should be populated immediately');
test.done();
},
parsing_and_serializing_entities: function(test) {
var html = '<html><body><a href="http://example.com/?a=b&c=d"><æ☺foo</a>';
var document = jsdom.jsdom(html);
var anchor = document.getElementsByTagName('a')[0];
test.strictEqual(anchor.getAttribute('href'), 'http://example.com/?a=b&c=d',
"href attribute value should be deentitified");
test.strictEqual(anchor.firstChild.nodeValue, '<æ☺foo',
"nodeValue of text node should be deentitified");
test.ok(anchor.outerHTML.indexOf('http://example.com/?a=b&c=d') !== -1,
"outerHTML of anchor href should be entitified");
test.ok(anchor.innerHTML.indexOf("<") === 0,
"innerHTML of anchor should begin with <");
test.done();
},
parsing_and_serializing_unknown_entities: function (test) {
var html = '<html><body>&nowayjose;☺lah;	q;</body></html>';
var document = jsdom.jsdom(html);
test.strictEqual(document.body.firstChild.nodeValue, "&nowayjose;☺lah; q;",
"Unknown and unparsable entities should be handled like a browser would");
test.strictEqual(document.body.innerHTML, "&nowayjose;☺lah; q;",
"Unknown and unparsable entities should be handled like a browser would");
test.done();
},
entities_in_script_should_be_left_alone: function (test) {
var html = '<!DOCTYPE html><html><head></head><body><script>alert(""");</script></body></html>';
var document = jsdom.jsdom(html);
test.strictEqual(document.body.innerHTML, '<script>alert(""");</script>');
test.strictEqual(document.body.firstChild.innerHTML, 'alert(""");');
test.done();
},
document_title_and_entities: function (test) {
var html = '<html><head><title><b>Hello</b></title></head><body></body></html>';
var document = jsdom.jsdom(html);
test.strictEqual(document.title, "<b>Hello</b>",
"document.title should be the deentitified version of what was in \
the original HTML"
);
document.title = "<b>World</b>";
test.strictEqual(document.title, "<b>World</b>",
"When document.title is set programmatically to something looking like \
HTML tags, then read again, it should have the exact same value, no \
entification should take place"
);
document.title = "<b>World</b>";
test.strictEqual(document.title, "<b>World</b>",
"When document.title is set programmatically to something looking like \
HTML entities, then read again, it should have the exact same value, \
no deentification should take place"
);
test.done();
},
setting_and_getting_textContent: function (test) {
var html = '<html><head>\n<title><foo></title></head><body>Hello<span><span>, </span>world</span>!</body></html>';
var document = jsdom.jsdom(html);
test.strictEqual(document.textContent, null,
"textContent of document should be null"
);
test.strictEqual(document.head.textContent, '\n<foo>',
"textContent of document.head should be the initial whitespace plus the textContent of the document title"
);
test.strictEqual(
document.body.textContent,
"Hello, world!",
"textContent of document.body should be the concatenation of the textContent values of its child nodes"
);
test.strictEqual(
document.createTextNode('<b>World</b>').textContent,
'<b>World</b>',
"textContent of programmatically created text node should be identical to its nodeValue"
);
test.strictEqual(
document.createComment('<b>World</b>').textContent,
'<b>World</b>',
"textContent of programmatically created comment node should be identical to its nodeValue"
);
var frag = document.createDocumentFragment();
frag.appendChild(document.createTextNode('<foo><b></b>'));
frag.appendChild(document.createElement('div')).appendChild(document.createTextNode('<foo><b></b>'));
test.strictEqual(frag.textContent, '<foo><b></b><foo><b></b>',
"textContent of programmatically created document fragment should be the concatenation of the textContent values of its child nodes"
);
var div = document.createElement('div');
div.innerHTML = '&lt;b&gt;\nWorld&lt;/b&gt;<span></span><span><span></span></span><span>&lt;b&gt;World&lt;/b&gt;</span>';
test.strictEqual(div.textContent, '<b>\nWorld</b><b>W\orld</b>',
"textContent of complex programmatically created <div> should be the \
concatenation of the textContent values of its child nodes"
);
test.done();
},
allow_ender_to_run : function(test) {
jsdom.env('<a />', [__dirname + '/files/ender-qwery.js'], function(e, w) {
test.ok(!e, 'no errors');
test.ok(w.ender, 'ender exists');
test.ok(w.$, 'window contains $');
test.done();
});
},
// see: https://github.com/tmpvar/jsdom/issues/259
issue_259 : function(test) {
try {
jsdom.jsdom('<!DOCTYPE svg>\n<svg version="1.1"></svg>');
} catch (e) {
console.log(e);
test.ok(false, 'Incomplete doctype should not throw an error');
}
test.done();
},
issues_230_259 : function(test) {