This repository has been archived by the owner on Dec 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 517
/
index.js
1381 lines (1176 loc) · 43.7 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
require('jsdom'); // work-around for node.js import of jsdom Windows.js before jsdom living module
const assert = require('assert');
const Assert = require('./assert');
const Bluebird = require('bluebird');
const Tabs = require('./tabs');
const Console = require('./console');
const Cookies = require('./cookies');
const debug = require('debug');
const DOM = require('./dom');
const { EventEmitter } = require('events');
const EventLoop = require('./eventloop');
const { format } = require('util');
const Fetch = require('./fetch');
const File = require('fs');
const Mime = require('mime');
const ms = require('ms');
const Path = require('path');
const Pipeline = require('./pipeline');
const reroute = require('./reroute');
const Storages = require('./storage');
const Tough = require('tough-cookie');
const { Cookie } = Tough;
const URL = require('url');
const Utils = require('jsdom/lib/jsdom/utils');
const { idlUtils } = require('./dom/impl');
// Version number. We get this from package.json.
const VERSION = require(`${__dirname}/../package.json`).version;
// Browser options you can set when creating new browser, or on browser instance.
const BROWSER_OPTIONS = ['features', 'headers', 'waitDuration',
'proxy', 'referrer', 'silent', 'site', 'strictSSL', 'userAgent',
'language', 'runScripts', 'localAddress'];
// These features are set on/off by default.
// Note that default values are actually prescribed where they are used,
// by calling hasFeature with name and default
const DEFAULT_FEATURES = 'scripts no-css no-img iframe';
const MOUSE_EVENT_NAMES = ['mousedown', 'mousemove', 'mouseup'];
// Use the browser to open up new windows and load documents.
//
// The browser maintains state for cookies and local storage.
class Browser extends EventEmitter {
constructor(options = {}) {
super();
// Used for assertions
this.assert = new Assert(this);
this.cookies = new Cookies();
// Shared by all windows.
this.console = new Console(this);
// Start with no this referrer.
this.referrer = null;
// Open tabs.
this.tabs = new Tabs(this);
// New pipeline for this browser.
this.pipeline = new Pipeline(this);
// The browser event loop.
this._eventLoop = new EventLoop(this);
// Returns all errors reported while loading this window.
this.errors = [];
this._storages = new Storages();
// The window that is currently in scope, some JS functions need this, e.g.
// when closing a window, you need to determine whether caller (window in
// scope) is same as window.opener
this._windowInScope = null;
this._debug = Browser._debug;
// Message written to window.console. Level is log, info, error, etc.
//
// All output goes to stdout, except when browser.silent = true and output
// only shown when debugging (DEBUG=zombie).
this
.on('console', (level, message)=> {
if (this.silent)
this._debug(`>> ${message}`);
else
console.log(message);
})
.on('log', (...args)=> {
// Message written to browser.log.
this._debug(format(...args));
});
// Logging resources
this
.on('request', (request)=> request)
.on('response', (request, response)=> {
this._debug('%s %s => %s', request.method, response.url, response.status);
})
.on('redirect', (request, response)=> {
this._debug('%s %s => %s %s', request.method, request.url, response.status, response.headers.get('Location'));
})
.on('loaded', (document)=> {
this._debug('Loaded document %s', document.location.href);
})
.on('xhr', (eventName, url)=> {
this._debug('XHR %s %s', eventName, url);
});
// Logging windows/tabs/navigation
this
.on('opened', (window)=> {
this._debug('Opened window %s %s', window.location.href, window.name || '');
})
.on('closed', (window)=> {
this._debug('Closed window %s %s', window.location.href, window.name || '');
});
// Switching tabs/windows fires blur/focus event on active window/element
this
.on('active', (window)=> {
// Window becomes inactive
const winFocus = window.document.createEvent('HTMLEvents');
winFocus.initEvent('focus', false, false);
window.dispatchEvent(winFocus);
if (window.document.activeElement) {
const elemFocus = window.document.createEvent('HTMLEvents');
elemFocus.initEvent('focus', false, false);
window.document.activeElement.dispatchEvent(elemFocus);
}
})
.on('inactive', (window)=> {
// Window becomes inactive
if (window.document.activeElement) {
const elemBlur = window.document.createEvent('HTMLEvents');
elemBlur.initEvent('blur', false, false);
window.document.activeElement.dispatchEvent(elemBlur);
}
const winBlur = window.document.createEvent('HTMLEvents');
winBlur.initEvent('blur', false, false);
window.dispatchEvent(winBlur);
});
// Logging navigation
this
.on('link', (url)=> {
this._debug('Follow link to %s', url);
})
.on('submit', (url)=> {
this._debug('Submit form to %s', url);
});
// Logging event loop
this._eventLoop
.on('setTimeout', (fn, delay)=> {
this._debug('Fired setTimeout after %dms delay', delay);
this.emit('setTimeout', fn, delay);
})
.on('setInterval', (fn, interval)=> {
this._debug('Fired setInterval every %dms', interval);
this.emit('setInterval', fn, interval);
})
.on('serverEvent', ()=> {
this._debug('Server initiated event');
this.emit('serverEvent');
})
.on('idle', (timedOut)=> {
if (timedOut)
this._debug('Event loop timed out');
else
this._debug('Event loop is empty');
this.emit('idle');
})
.on('error', (error)=> {
this.emit('error', error);
});
// Make sure we don't blow up Node when we get a JS error, but dump error to console. Also, catch any errors
// reported while processing resources/JavaScript.
this.on('error', (error)=> {
this.errors.push(error);
this._debug(error.stack);
});
// Sets the browser options.
options = options || {};
for (let name of BROWSER_OPTIONS)
this[name] = options.hasOwnProperty(name) ?
options[name] :
(Browser[name] || null);
// Last, run all extensions in order.
for (let extension of Browser._extensions)
extension(this);
}
// Returns true if the given feature is enabled.
//
// If the feature is listed, then it is enabled. If the feature is listed
// with "no-" prefix, then it is disabled. If the feature is missing, return
// the default value.
hasFeature(name, defaultValue = true) {
const features = (this.features || '').split(/\s+/);
return ~features.indexOf(name) ? true :
~features.indexOf(`no-${name}`) ? false :
defaultValue;
}
// Return a new browser with a snapshot of this browser's state.
// Any changes to the forked browser's state do not affect this browser.
fork() {
throw new Error('Not implemented');
}
// Windows
// -------
// Returns the currently open window
get window() {
return this.tabs.current;
}
// Open new browser window.
open({ url, name, referrer } = {}) {
return this.tabs.open({ url, name, referrer });
}
// browser.error => Error
//
// Returns the last error reported while loading this window.
get error() {
return this.errors[this.errors.length - 1];
}
// Events
// ------
// Waits for the browser to complete loading resources and processing JavaScript events.
//
// Accepts two parameters, both optional:
// options - Options that determine how long to wait (see below)
// callback - Called with error or null and browser
//
// To determine how long to wait:
// duration - Do not wait more than this duration (milliseconds or string of
// the form "5s"). Defaults to "5s" (see Browser.waitDuration).
// element - Stop when this element(s) appear in the DOM.
// function - Stop when function returns true; this function is called with
// the active window and expected time to the next event (0 to
// Infinity).
//
// As a convenience you can also pass the duration directly.
//
// Without a callback, this method returns a promise.
wait(options, callback) {
assert(this.window, new Error('No window open'));
if (arguments.length === 1 && typeof options === 'function')
[callback, options] = [options, null];
assert(!callback || typeof callback === 'function', 'Second argument expected to be a callback function or null');
// Support all sort of shortcuts for options. Unofficial.
const duration =
(typeof options === 'number') ? options :
(typeof options === 'string') ? options :
(options && options.duration || this.waitDuration || '5s');
// Support 500 (ms) as well as "5s"
const waitDuration = ms(duration.toString());
function completionFromElement(element) {
return function(window) {
return !!window.document.querySelector(element);
};
}
const completionFunction =
(typeof options === 'function') ? options :
(options && options.element) ? completionFromElement(options.element) :
(options && options.function);
const { _eventLoop } = this;
if (callback)
_eventLoop.wait(waitDuration, completionFunction, callback);
else
return Bluebird.promisify(_eventLoop.wait.bind(_eventLoop))(waitDuration, completionFunction);
}
// Waits for the browser to get a single event from any EventSource,
// then completes loading resources and processing JavaScript events.
//
// Accepts an optional callback which is called with error or nothing
//
// Without a callback, this method returns a promise.
waitForServer(options, callback) {
assert(this.window, new Error('No window open'));
if (arguments.length === 1 && typeof options === 'function')
[callback, options] = [options, null];
if (callback) {
this._eventLoop.once('serverEvent', ()=> {
this.wait(options, callback);
});
return null;
}
return new Promise((resolve)=> {
this._eventLoop.once('serverEvent', ()=> {
resolve(this.wait(options, null));
});
});
}
// Various methods use this with a callback, or return a lazy promise (e.g.
// visit, click, fire)
_wait(options, callback) {
if (callback) {
this.wait(options, callback);
return null;
}
let promise = null;
const lazyResolve = ()=> {
if (!promise)
promise = this.wait(options, null);
return promise;
};
// Returns equivalent of a promise that only starts evaluating when you
// call then() or catch() on it.
return {
then(resolved, rejected) {
return lazyResolve().then(resolved, rejected);
},
catch(rejected) {
return lazyResolve().then(null, rejected);
}
};
}
// Fire a DOM event. You can use this to simulate a DOM event, e.g. clicking
// a link. These events will bubble up and can be cancelled. Like `wait`
// this method takes an optional callback and returns a promise.
//
// name - Even name (e.g `click`)
// target - Target element (e.g a link)
// callback - Called with error or nothing
//
// If called without callback, returns a promise
fire(selector, eventName, callback) {
assert(this.window, 'No window open');
const target = this.query(selector);
assert(target && target.dispatchEvent, 'No target element (note: call with selector/element, event name and callback)');
const eventType = ~MOUSE_EVENT_NAMES.indexOf(eventName) ? 'MouseEvents' : 'HTMLEvents';
const event = this.document.createEvent(eventType);
event.initEvent(eventName, true, true);
target.dispatchEvent(event);
if (selector.tagName === 'BUTTON' || selector.tagName == 'INPUT') selector._click(event);
return this._wait(null, callback);
}
// Click on the element and returns a promise.
//
// selector - Element or CSS selector
// callback - Called with error or nothing
//
// If called without callback, returns a promise
click(selector, callback) {
return this.fire(selector, 'click', callback);
}
// Dispatch asynchronously. Returns true if preventDefault was set.
dispatchEvent(selector, event) {
assert(this.window, 'No window open');
const target = this.query(selector);
return target.dispatchEvent(event);
}
// Accessors
// ---------
// browser.queryAll(selector, context?) => Array
//
// Evaluates the CSS selector against the document (or context node) and return array of nodes.
// (Unlike `document.querySelectorAll` that returns a node list).
queryAll(selector = 'html', context = this.document) {
assert(this.document && this.document.documentElement, 'No open window with an HTML document');
if (Array.isArray(selector))
return selector;
if (selector instanceof DOM.Element)
return [selector];
if (selector) {
const elements = context.querySelectorAll(selector);
return Array.from(elements);
} else
return [];
}
// browser.query(selector, context?) => Element
//
// Evaluates the CSS selector against the document (or context node) and return an element.
query(selector = 'html', context = this.document) {
assert(this.document && this.document.documentElement, 'No open window with an HTML document');
if (selector instanceof DOM.Element)
return selector;
return selector ? context.querySelector(selector) : context;
}
// WebKit offers this.
$$(selector, context) {
return this.query(selector, context);
}
// browser.querySelector(selector) => Element
//
// Select a single element (first match) and return it.
//
// selector - CSS selector
//
// Returns an Element or null
querySelector(selector) {
assert(this.document && this.document.documentElement, 'No open window with an HTML document');
return this.document.querySelector(selector);
}
// browser.querySelectorAll(selector) => NodeList
//
// Select multiple elements and return a static node list.
//
// selector - CSS selector
//
// Returns a NodeList or null
querySelectorAll(selector) {
assert(this.document && this.document.documentElement, 'No open window with an HTML document');
return this.document.querySelectorAll(selector);
}
// browser.text(selector, context?) => String
//
// Returns the text contents of the selected elements.
//
// selector - CSS selector (if missing, entire document)
// context - Context element (if missing, uses document)
//
// Returns a string
text(selector = 'html', context = this.document) {
assert(this.document, 'No window open');
if (this.document.documentElement)
return this.queryAll(selector, context)
.map(elem => elem.textContent)
.join('')
.trim()
.replace(/\s+/g, ' ');
else
return (this.source ? this.source.toString : '');
}
// browser.html(selector?, context?) => String
//
// Returns the HTML contents of the selected elements.
//
// selector - CSS selector (if missing, entire document)
// context - Context element (if missing, uses document)
//
// Returns a string
html(selector = 'html', context = this.document) {
assert(this.document, 'No window open');
if (this.document.documentElement)
return this.queryAll(selector, context)
.map(elem => elem.outerHTML.trim())
.join('');
else
return (this.source ? this.source.toString : '');
}
// browser.xpath(expression, context?) => XPathResult
//
// Evaluates the XPath expression against the document (or context node) and return the XPath result. Shortcut for
// `document.evaluate`.
xpath(expression, context = null) {
return this.document.evaluate(expression, context || this.document.documentElement, null, DOM.XPathResult.ANY_TYPE);
}
// browser.document => Document
//
// Returns the main window's document. Only valid after opening a document (see `browser.open`).
get document() {
return this.window && this.window.document;
}
// browser.body => Element
//
// Returns the body Element of the current document.
get body() {
return this.querySelector('body');
}
// Element that has the current focus.
get activeElement() {
return this.document && this.document.activeElement;
}
// Close all windows, clean state, etc. This doesn't do anything the garbage
// collector doesn't already do, so you don't need to call this.
//
// But because it destroys the browser state, it's quite useful for detecting
// weird behavior bugs, e.g. an event loop that keeps running. That's why
// the test suite uses this method.
destroy() {
if (this.tabs) {
this.tabs.closeAll();
this.tabs = null;
}
}
// Navigation
// ----------
// browser.visit(url, callback?)
//
// Loads document from the specified URL, processes events and calls the callback, or returns a promise.
visit(url, options, callback) {
if (arguments.length < 3 && typeof options === 'function')
[options, callback] = [{}, options];
const site = /^(https?:|file:)/i.test(this.site) ? this.site : `http://${this.site || 'localhost'}/`;
url = URL.resolve(site, url);
if (this.window)
this.tabs.close(this.window);
this.errors = [];
this.tabs.open({ url: url, referrer: this.referrer });
return this._wait(options, callback);
}
// browser.load(html, callback)
//
// Loads the HTML, processes events and calls the callback.
//
// Without a callback, returns a promise.
load(html, callback) {
if (this.window)
this.tabs.close(this.window);
this.errors = [];
this.tabs.open({ html: html });
return this._wait(null, callback);
}
// browser.location => Location
//
// Return the location of the current document (same as `window.location`).
get location() {
return this.window && this.window.location;
}
// browser.location = url
//
// Changes document location, loads new document if necessary (same as setting `window.location`).
set location(url) {
if (this.window)
this.window.location = url;
else
this.open({ url: url });
}
// browser.url => String
//
// Return the URL of the current document (same as `document.URL`).
get url() {
return this.window && this.window.location.href;
}
// browser.link(selector) : Element
//
// Finds and returns a link by its text content or selector.
link(selector) {
assert(this.document && this.document.documentElement, 'No open window with an HTML document');
// If the link has already been queried, return itself
if (selector instanceof DOM.Element)
return selector;
try {
const link = this.querySelector(selector);
if (link && link.tagName === 'A')
return link;
} catch (error) {
/* eslint no-empty:0 */
}
for (let elem of Array.from(this.querySelectorAll('body a')))
if (elem.textContent.trim() === selector)
return elem;
return null;
}
// browser.clickLink(selector, callback)
//
// Clicks on a link. Clicking on a link can trigger other events, load new page, etc: use a callback to be notified of
// completion. Finds link by text content or selector.
//
// selector - CSS selector or link text
// callback - Called with two arguments: error and browser
clickLink(selector, callback) {
const link = this.link(selector);
assert(link, `No link matching '${selector}'`);
return this.click(link, callback);
}
// Return the history object.
get history() {
if (!this.window)
this.open();
return this.window.history;
}
// Navigate back in history.
back(callback) {
this.window.history.back();
return this._wait(null, callback);
}
// Reloads current page.
reload(callback) {
this.window.location.reload();
return this._wait(null, callback);
}
// browser.saveHistory() => String
//
// Save history to a text string. You can use this to load the data later on using `browser.loadHistory`.
saveHistory() {
return this.window.history.save();
}
// browser.loadHistory(String)
//
// Load history from a text string (e.g. previously created using `browser.saveHistory`.
loadHistory(serialized) {
this.window.history.load(serialized);
}
// Forms
// -----
// browser.field(selector) : Element
//
// Find and return an input field (`INPUT`, `TEXTAREA` or `SELECT`) based on a CSS selector, field name (its `name`
// attribute) or the text value of a label associated with that field (case sensitive, but ignores leading/trailing
// spaces).
field(selector) {
assert(this.document && this.document.documentElement, 'No open window with an HTML document');
// If the field has already been queried, return itself
if (selector instanceof DOM.Element)
return selector;
try {
// Try more specific selector first.
const field = this.query(selector);
if (field && (field.tagName === 'INPUT' || field.tagName === 'TEXTAREA' || field.tagName === 'SELECT'))
return field;
} catch (error) {
// Invalid selector, but may be valid field name
}
// Use field name (case sensitive).
for (let elem of this.queryAll('input[name],textarea[name],select[name]'))
if (elem.getAttribute('name') === selector)
return elem;
// Try finding field from label.
for (let label of this.queryAll('label'))
if (label.textContent.trim() === selector) {
// nLabel can either reference field or enclose it
const forAttr = label.getAttribute('for');
return forAttr ?
this.document.getElementById(forAttr) :
label.querySelector('input,textarea,select');
}
return null;
}
// browser.focus(selector, callback) : null or lazy Promise
//
// Turns focus to the selected input field. Shortcut for calling `field(selector).focus()`.
// callback - Called with error or nothing
//
// If called without callback, returns a promise
focus(selector, callback) {
const field = this.field(selector) || this.query(selector);
assert(field, `No form field matching '${selector}'`);
field.focus();
return this._wait(null, callback);
}
// browser.fill(selector, value, callback) => null or lazy Promise
//
// Fill in a field: input field or text area.
//
// selector - CSS selector, field name or text of the field label
// value - Field value
// callback - Called with error or nothing
//
// If called without callback, returns a promise
fill(selector, value, callback) {
const field = this.field(selector);
assert(field && (field.tagName === 'TEXTAREA' || (field.tagName === 'INPUT')), `No INPUT matching '${selector}'`);
assert(!field.disabled, 'This INPUT field is disabled');
assert(!field.readonly, 'This INPUT field is readonly');
// Switch focus to field, change value and emit the input event (HTML5)
field.focus();
// `field.value = value` does not work if there is a custom property descriptor, e.g. in React
// TODO: check what the actual spec compliant way of doing this is
const descriptor = Object.getOwnPropertyDescriptor(field.constructor.prototype, 'value');
descriptor.set.call(field, value);
this.fire(field, 'input', false);
// Switch focus out of field, if value changed, this will emit change event
field.blur();
return this._wait(null, callback);
}
_setCheckbox(selector, value, callback) {
const field = this.field(selector);
assert(field && field.tagName === 'INPUT' && field.type === 'checkbox', `No checkbox INPUT matching '${selector}'`);
assert(!field.disabled, 'This INPUT field is disabled');
assert(!field.readonly, 'This INPUT field is readonly');
if (field.checked ^ value)
field.click();
return this.wait(null, callback);
}
// browser.check(selector, callback) => null or lazy Promise
//
// Checks a checkbox.
//
// selector - CSS selector, field name or text of the field label
// callback - called with error or nothing.
//
// If called without callback, returns a promise
check(selector, callback) {
return this._setCheckbox(selector, true, callback);
}
// browser.uncheck(selector, callback) => null or lazy Promise
//
// Unchecks a checkbox.
//
// selector - CSS selector, field name or text of the field label
// callback - called with error or nothing.
//
// If called without callback, returns a promise
uncheck(selector, callback) {
return this._setCheckbox(selector, false, callback);
}
// browser.choose(selector, callback) => null or lazy Promise
//
// Selects a radio box option.
//
// selector - CSS selector, field value or text of the field label
// callback - called with error or nothing.
//
// If called without callback, returns a promise
choose(selector, callback) {
const field = this.field(selector) || this.field(`input[type=radio][value=\'${escape(selector)}\']`);
assert(field && field.tagName === 'INPUT' && field.type === 'radio', `No radio INPUT matching '${selector}'`);
field.click();
return this._wait(null, callback);
}
_findOption(selector, value) {
const field = this.field(selector);
assert(field && field.tagName === 'SELECT', `No SELECT matching '${selector}'`);
assert(!field.disabled, 'This SELECT field is disabled');
assert(!field.readonly, 'This SELECT field is readonly');
const options = Array.from(field.options);
for (let option of options)
if (option.value === value)
return option;
for (let option of options)
if (option.label === value)
return option;
for (let option of options)
if (option.textContent.trim() === value)
return option;
throw new Error(`No OPTION '${value}'`);
}
// browser.select(selector, value) => null or lazy Promise
//
// Selects an option.
//
// selector - CSS selector, field name or text of the field label
// value - Value (or label) or option to select
// callback - called with error or nothing.
//
// If called without callback, returns a promise
select(selector, value, callback) {
const option = this._findOption(selector, value);
return this.selectOption(option, callback);
}
// browser.selectOption(option) => null or lazy Promise
//
// Selects an option.
//
// option - option to select
// callback - called with error or nothing.
//
// If called without callback, returns a promise
selectOption(selector, callback) {
const option = this.query(selector);
if (option && !option.selected) {
const select = this.xpath('./ancestor::select', option).iterateNext();
select.focus();
option.selected = true;
this.fire(select, 'change', false);
}
return this._wait(null, callback);
}
// browser.unselect(selector, value, callback) => null or lazy Promise
//
// Unselects an option.
//
// selector - CSS selector, field name or text of the field label
// value - Value (or label) or option to unselect
// callback - called with error or nothing.
//
// If called without callback, returns a promise
unselect(selector, value, callback) {
const option = this._findOption(selector, value);
return this.unselectOption(option, callback);
}
// browser.unselectOption(option, callback) => null or lazy Promise
//
// Unselects an option.
//
// selector - selector or option to unselect
// callback - called with error or nothing.
//
// If called without callback, returns a promise
unselectOption(selector, callback) {
const option = this.query(selector);
if (option && option.selected) {
const select = this.xpath('./ancestor::select', option).iterateNext();
assert(select.multiple, 'Cannot unselect in single select');
option.selected = false;
select.focus();
this.fire(select, 'change', false);
}
return this._wait(null, callback);
}
// browser.attach(selector, filename, callback) => null or lazy Promise
//
// Attaches a file to the specified input field. The second argument is the file name.
// callback - called with error or nothing.
//
// If called without callback, returns a promise
attach(selector, filename, callback) {
const field = this.field(selector);
assert(field && field.tagName === 'INPUT' && field.type === 'file', `No file INPUT matching '${selector}'`);
if (filename) {
const stat = File.statSync(filename);
const file = new (this.window.File)();
file.name = Path.basename(filename);
file.type = Mime.getType(filename);
file.size = stat.size;
Object.defineProperty(field, 'value', {value: filename});
const oldFiles = field.files;
if (typeof(oldFiles) !== 'array')
// JSDOM does not support an API to mock a list of files, and the default
// type of the 'files' attribute is a FileList object.
Object.defineProperty(field, 'files', {
value: []
});
field.files.push(file);
}
field.focus();
this.fire(field, 'change', false);
return this._wait(null, callback);
}
// browser.button(selector) : Element
//
// Finds a button using CSS selector, button name or button text (`BUTTON` or `INPUT` element).
//
// selector - CSS selector, button name or text of BUTTON element
button(selector) {
assert(this.document && this.document.documentElement, 'No open window with an HTML document');
// If the button has already been queried, return itself
if (selector instanceof DOM.Element)
return selector;
try {
const button = this.querySelector(selector);
if (button && (button.tagName === 'BUTTON' || button.tagName === 'INPUT'))
return button;
} catch (error) {
}
for (let elem of Array.from(this.querySelectorAll('button')))
if (elem.textContent.trim() === selector)
return elem;
const inputs = Array.from(this.querySelectorAll('input[type=submit],input[type=button],input[type=reset],button'));
for (let input of inputs)
if (input.name === selector)
return input;
for (let input of inputs)
if (input.value === selector)
return input;
return null;
}
// browser.pressButton(selector, callback)
//
// Press a button (button element or input of type `submit`). Typically this will submit the form. Use the callback
// to wait for the from submission, page to load and all events run their course.
//
// selector - CSS selector, button name or text of BUTTON element
// callback - Called with two arguments: null and browser
pressButton(selector, callback) {
const button = this.button(selector);
assert(button, `No BUTTON '${selector}'`);
assert(!button.disabled, 'This button is disabled');
button.focus();
const impl = idlUtils.implForWrapper(button);
return this.fire(button, 'click', callback);
}
// -- Cookies --
// Returns cookie that best matches the identifier.
//
// identifier - Identifies which cookie to return
// allProperties - If true, return all cookie properties, other just the value
//
// Identifier is either the cookie name, in which case the cookie domain is
// determined from the currently open Web page, and the cookie path is "/".
//
// Or the identifier can be an object specifying:
// name - The cookie name
// domain - The cookie domain (defaults to hostname of currently open page)
// path - The cookie path (defaults to "/")
//
// Returns cookie value, or cookie object (see setCookie).
getCookie(identifier, allProperties) {
identifier = this._cookieIdentifier(identifier);
assert(identifier.name, 'Missing cookie name');
assert(identifier.domain, 'No domain specified and no open page');
const cookie = this.cookies.select(identifier)[0];
return cookie ?
(allProperties ?
this._cookieProperties(cookie) :
cookie.value) :
null;
}
// Deletes cookie that best matches the identifier.
//
// identifier - Identifies which cookie to return