-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathdefaults.js
More file actions
895 lines (805 loc) · 33.7 KB
/
Copy pathdefaults.js
File metadata and controls
895 lines (805 loc) · 33.7 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
/**
* @license
* Copyright CERN and copyright holders of ALICE O2. This software is
* distributed under the terms of the GNU General Public License v3 (GPL
* Version 3), copied verbatim in the file "COPYING".
*
* See http://alice-o2.web.cern.ch/license for full licensing information.
*
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
const chai = require('chai');
const puppeteer = require('puppeteer');
const pti = require('puppeteer-to-istanbul');
const { server } = require('../../lib/application');
const { buildUrl } = require('@aliceo2/web-ui');
const dateAndTime = require('date-and-time');
const path = require('path');
const { expect } = chai;
const testToken = server.http.o2TokenService.generateToken(
0,
'anonymous',
'Anonymous',
'admin',
);
/**
* Overrides the given URL to add authentication information to it
*
* @param {string} url the URL to authenticate
* @return {string} the authenticated URL
*/
const authenticateUrl = (url) => {
const authenticatedUrl = new URL(url);
authenticatedUrl.searchParams.set('personid', 0);
authenticatedUrl.searchParams.set('username', 'anonymous');
authenticatedUrl.searchParams.set('name', 'Anonymous');
authenticatedUrl.searchParams.set('access', 'admin');
authenticatedUrl.searchParams.set('token', testToken);
return authenticatedUrl.toString();
};
/**
* Returns the URL with correct port postfixed.
* @returns {string} URL specific to the port specified by user/host.
*/
const getUrl = () => `http://localhost:${server.address().port}`;
/**
* Constructor to build elements before tests start.
*
* @returns {Promise<Array>} Array of multiple objects, consisting of Page, Browser and Url.
*/
module.exports.defaultBefore = async () => {
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-gpu', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
page.setDefaultTimeout(1500);
page.setDefaultNavigationTimeout(5000);
await Promise.all([
page.coverage.startJSCoverage({ resetOnNavigation: false }),
page.coverage.startCSSCoverage(),
]);
return [page, browser, getUrl()];
};
/**
* Destructor to clean up after tests are finished.
* @param {Object} page Puppeteer page object
* @param {Object} browser Browser object to run tests on
* @returns {Promise<Array>} Array of multiple objects, consisting of Page and Browser.
*/
module.exports.defaultAfter = async (page, browser) => {
const [jsCoverage, cssCoverage] = await Promise.all([
page.coverage.stopJSCoverage(),
page.coverage.stopCSSCoverage(),
]);
pti.write([...jsCoverage, ...cssCoverage].filter(({ url = '' } = {}) => url.match(/\.(js|css)$/)), {
includeHostname: false,
storagePath: './.nyc_output/lib/public',
});
await browser.close();
return [page, browser];
};
/**
* Trigger a download and wait for it to be finished
*
* @param {puppeteer.Page} page puppeteer page
* @param {function} trigger function to trigger the expected download
* @return {Promise} resolves with de download path
*/
exports.waitForDownload = async (page, trigger) => {
const downloadPath = path.resolve('./download');
// Check accessibility on frontend
const session = await page.createCDPSession();
await session.send('Browser.setDownloadBehavior', {
behavior: 'allow',
downloadPath,
eventsEnabled: true,
});
await Promise.all([
new Promise((resolve, reject) => {
session.on('Browser.downloadProgress', (event) => {
if (event.state === 'completed') {
resolve('download completed');
} else if (event.state === 'canceled') {
reject(new Error('download canceled'));
}
});
setTimeout(() => reject(new Error('Download timeout after 5000 ms')), 5000);
}),
trigger(),
]);
return downloadPath;
};
/**
* Resolves after a given timeout (temporary replacement for puppeteer Page.waitForTimeout)
*
* @deprecated use an appropriate waitForSelector instead
*
* @param {number} timeout the timeout to wait (in ms)
* @return {Promise<void>} resolves once the timeout has been elapsed
*/
const waitForTimeout = (timeout) => new Promise((res) => setTimeout(res, timeout));
/**
* @deprecated
*/
module.exports.waitForTimeout = waitForTimeout;
/**
* Waits for the number of table rows to meet the expected size.
*
* @param {puppeteer.Page} page - The puppeteer page where the table is located.
* @param {number} expectedSize - The expected number of table rows, excluding rows marked as loading or empty.
* @return {Promise<void>} Resolves once the expected number of rows is met, or the timeout is reached.
*/
const waitForTableToLength = async (page, expectedSize) => {
try {
await page.waitForFunction(
(expectedSize) => document.querySelectorAll('table tbody tr:not(.loading-row):not(.empty-row)').length === expectedSize,
{},
expectedSize,
);
} catch {
const actualSize = (await page.$$('tbody tr')).length;
const isThereLoadingRow = !!(await page.$$('table body tr.loading-row'))
throw new Error(`Expected table of length ${expectedSize}, but got ${actualSize} ${isThereLoadingRow ? ', loading-row' : ''}`);
}
};
module.exports.waitForTableLength = waitForTableToLength;
/**
* Wait for the total number of elements to be the expected one
*
* @param {puppeteer.Page} page The puppeteer page where the table is located
* @param {number} amount the expected amount of items
* @return {Promise<void>} resolves once the expected amount is present
*/
module.exports.waitForTableTotalRowsCountToEqual = async (page, amount) => {
try {
await page.waitForSelector('#totalRowsCount');
await page.waitForFunction(
(amount) => document.querySelector('#totalRowsCount').innerText === `${amount}`,
{},
amount,
);
} catch {
const actualCount = (await page.$$('#totalRowsCount')).innerText;
throw new Error(`Expected total rows count ${amount}, but got ${actualCount}`);
}
};
/**
* Wait for the first index of table items to be the expected one
*
* @param {puppeteer.Page} page the puppeteer page where the table is located
* @param {number} index the expected index of the first item
* @return {Promise<void>} resolves once the first item has the specified index
*/
module.exports.waitForTableFirstRowIndexToEqual = async (page, index) => {
await page.waitForFunction(
(index) => document.querySelector('#firstRowIndex').innerText === `${index}`,
{},
index,
);
};
/**
* Waits for the table on the page to be empty.
*
* @param {puppeteer.Page} page - The puppeteer page where the table is located.
* @param {number} [timeout=500] - Optional timeout in milliseconds before the function times out.
* @return {Promise<void>} Resolves once the table is empty, or the timeout is reached.
*/
const waitForEmptyTable = async (page, timeout = 500) => {
await page.waitForSelector('table tbody tr.empty-row', { timeout: timeout });
};
module.exports.waitForEmptyTable = waitForEmptyTable;
/**
* Wait for the first row of the page to have a given id
*
* @param {puppeteer.Page} page Puppeteer current page
* @param {string} id the expected id
* @return {Promise<puppeteer.ElementHandle>} resolves with the first row element handle once it has the right id
*/
module.exports.waitForFirstRowToHaveId = async (page, id) => page.waitForSelector(`tbody tr:first-child#${id}`);
/**
* Execute the given navigation function and wait for navigation
*
* @param {puppeteer.Page} page the puppeteer page
* @param {function} navigateFunction function to call to initiate navigation
* @return {Promise<*>} resolves once the navigation finished
*/
const waitForNavigation = (page, navigateFunction) => Promise.all([
page.waitForNavigation(),
navigateFunction(),
]);
exports.waitForNavigation = waitForNavigation;
/**
* Waits till selector is visible and then clicks element.
* @param {Object} page Puppeteer page object.
* @param {string} selector Css selector.
* @param {boolean} [jsClick=false] if true, use js native click on the element instead of page's click method (useful if element is not visible)
* @returns {Promise} Whether the element was clickable or not.
*/
module.exports.pressElement = async (page, selector, jsClick = false) => {
const elementHandler = await page.waitForSelector(selector);
if (jsClick) {
await elementHandler.evaluate((element) => element.click());
} else {
await elementHandler.click(selector);
}
};
/**
* Reload the current page and wait for it to be loaded
* @param {Page} puppeteerPage Puppeteer page object.
* @return {Promise} resolves when the page has loaded
* @deprecated avoid using this function, reloading the full page is very slow
*/
module.exports.reloadPage = (puppeteerPage) => goTo(puppeteerPage, puppeteerPage.url());
/**
* Navigates to a specific URL and waits until everything is loaded.
*
* @param {puppeteer.Page} page puppeteer page object
* @param {string} url the URL to navigate to
* @param {object} [options] navigation options
* @param {boolean} [options.authenticate] if true, the navigation request will be authenticated with a token and test user information
* @param {number} [options.redrawDuration] the estimated time to wait for the page to redraw
* @returns {Promise} resolves with the navigation response
*/
const goTo = async (page, url, options) => {
const { authenticate = true } = options ?? {};
if (authenticate) {
url = authenticateUrl(url);
}
const response = await page.goto(url, { waitUntil: 'load' });
// Wait for navbar title to be there, which mean that a first render has been done
await page.waitForSelector('#navbar-title', { timeout: 5000 });
return response;
};
/**
* Goes to a specific page and waits until everything is loaded.
* @param {Page} puppeteerPage Puppeteer page object.
* @param {string} pageKey Value of pageKey in: URL/?page={pageKey}&...
* @param {object} [options] navigation options
* @param {boolean} [options.authenticate] if true, the navigation request will be authenticated with a token and test user information
* @param {object} [options.queryParameters] query parameters to add to the page's URL
* @returns {Promise} Switches the user to the correct page.
*/
module.exports.goToPage = (puppeteerPage, pageKey, options) => {
const { queryParameters = {} } = options || {};
const url = buildUrl(getUrl(), {
page: pageKey,
...queryParameters,
});
return goTo(puppeteerPage, url);
};
/**
* Debug helper function
* This function takes a screenshot of the current screen the page is at, and saves it to
* database/storage/screenshot.png
* @param {puppeteer.Page} page Puppeteer page object.
* @param {string} name Name of the screenshot taken. Useful when taking multiple in a row.
* @returns {*} None
*/
module.exports.takeScreenshot = async (page, name = 'screenshot') => {
await page.screenshot({
path: `/var/storage/${name}.png`,
type: 'png',
fullPage: true,
});
};
/**
* Special method built due to Puppeteer limitations: looks for the first row matching an ID in a table
* @param {Object} table An HTML element representing the entire run table
* @param {Object} page An object representing the browser page being used by Puppeteer
* @return {Promise<String>} The ID of the first matching row with data
*/
module.exports.getFirstRow = async (table, page) => {
for await (const child of table) {
const id = await page.evaluate((element) => element.id, child);
if (id.startsWith('row')) {
return id;
}
}
};
/**
* Return the inner text of all the cells of a given column of the first table found in the page
*
* @param {puppeteer.Page} page the puppeteer page
* @param {string} key the key of the column from which data must be retrieved
* @return {Promise<string[]>} resolves with the list of all cells inner texts
*/
const getColumnCellsInnerTexts = async (page, key) => page.$$eval(
`table tbody .column-${key}`,
(cells) => cells.map((cell) => cell.innerText),
);
module.exports.getColumnCellsInnerTexts = getColumnCellsInnerTexts;
/**
* Return the content of a table as an array (rows) of array (cells)
*
* @param {puppeteer.Page} page the puppeteer page
* @return {Promise<array<string[]>>} resolves with the table content
*/
module.exports.getTableContent = async (page) => {
await page.waitForSelector('table');
return JSON.parse(await page.evaluate(() => {
const rowsContent = [];
for (const row of document.querySelectorAll('table tbody tr')) {
const cellsContent = [];
rowsContent.push(cellsContent);
for (const cell of row.querySelectorAll('td')) {
cellsContent.push(cell.innerText);
}
}
return JSON.stringify(rowsContent);
}));
};
/**
* Special method built to gather all currently visible data from given columns into array of objects
* @param {puppeteer.Page} page An object representing the browser page being used by Puppeteer
* @param {string[]} columnKeys The keys for the columns to gather entities of
* @return {Promise<Object<string, string>>} An array containing all table partial entities of a columns, in the order displayed by the browser
*/
module.exports.getTableDataSlice = async (page, columnKeys) => {
const result = [];
for (const row of await page.$$('table tbody tr')) {
const entity = {};
for (const columnKey of columnKeys) {
entity[columnKey] = await row.$eval(`td.column-${columnKey}`, ({ innerText }) => innerText);
}
result.push(entity);
}
return result;
};
/**
* Evaluate and return the text content of a given element handler
* @param {{evaluate}} elementHandler the puppeteer handler of the element to inspect
* @returns {Promise<string>} the html content
*/
const getInnerText = async (elementHandler) => await elementHandler.evaluate((element) => element.innerText);
module.exports.getInnerText = getInnerText;
/**
* Expect an element to have a given text
*
* @param {Object} page Puppeteer page object.
* @param {string} selector Css selector.
* @param {string} innerText Text to search for.
* @param {object} [options] eventual options
* @param {number} [options.timeout] Optional timeout
* @param {puppeteer.FrameWaitForFunctionOptions} [options.polling] Optional polling methods, see
* @return {Promise<void>} resolves once the text has been checked
*/
module.exports.expectInnerText = async (page, selector, innerText, options = {}) => {
const elementHandle = await page.waitForSelector(selector);
try {
await page.waitForFunction(
(selector, innerText) => document.querySelector(selector).innerText === innerText,
options,
selector,
innerText,
);
} catch (_) {
const actualInnerText = await getInnerText(elementHandle);
await elementHandle.dispose();
if (actualInnerText === innerText) {
// Timeout issue resolved by itself, simply return (kind of retry for free)
return;
}
throw new Error(`Expected innerText for ${selector} to be "${innerText}", got "${actualInnerText}"`);
}
await elementHandle.dispose();
};
/**
* Expect a given attribute of an element to have a given value
*
* @param {puppeteer.Page} page the puppeteer page
* @param {string} selector the selector of the element to look for attribute
* @param {string} attributeKey the key of the attribute to check
* @param {string} attributeValue the expected value
* @return {Promise<void>} resolves once the attribute has the expected value
*/
module.exports.expectAttributeValue = async (page, selector, attributeKey, attributeValue) => {
const elementHandle = await page.waitForSelector(selector);
try {
await page.waitForFunction(
(selector, attributeKey, attributeValue) => document.querySelector(selector).getAttribute(attributeKey) === attributeValue,
{},
selector,
attributeKey,
attributeValue,
);
} catch (_) {
const actualAttributeValue = await elementHandle.evaluate((element, attributeKey) => element.getAttribute(attributeKey), attributeKey);
await elementHandle.dispose();
throw new Error(`Expect attribute ${attributeKey} to be ${attributeValue}, got ${actualAttributeValue}`);
}
await elementHandle.dispose();
};
/**
* Expect an element to have a text valid against given validator
* @param {Object} page Puppeteer page object.
* @param {string} selector Css selector.
* @param {function<string, boolean>} validator text validator. It must return true if text is valid, return false or throw otherwise
* @return {Promise<void>} resolves once the text has been checked
*/
module.exports.expectInnerTextTo = async (page, selector, validator) => {
const element = await page.waitForSelector(selector);
const actualInnerText = await getInnerText(element);
expect(validator(actualInnerText), `"${actualInnerText}" is invalid with respect of given validator`).to.be.true;
};
/**
* Expect an element to have a text valid against given validator
* @param {Object} page Puppeteer page object.
* @param {string} selector Css selector.
* @param {function<string, boolean>} validator text validator. It must return true if text is valid, return false or throw otherwise
* @return {Promise<void>} resolves once the text has been checked
*/
module.exports.expectInnerTextTo = async (page, selector, validator) => {
const element = await page.waitForSelector(selector);
const actualInnerText = await getInnerText(element);
expect(validator(actualInnerText), `"${actualInnerText}" is invalid with respect of given validator`).to.be.true;
};
/**
* Evaluate and return the html content of a given element handler
* @param {{evaluate}} elementHandler the puppeteer handler of the element to inspect
* @returns {Promise<XPathResult>} the html content
*/
const getInnerHtml = async (elementHandler) => await elementHandler.evaluate((element) => element.innerHTML);
module.exports.getInnerHtml = getInnerHtml;
/**
* Return the selector of a popover that correspond to a popover trigger
*
* @param {object} popoverTrigger the puppeteer element of the popover trigger
* @return {Promise<string|null>} the popover selector
*/
exports.getPopoverSelector = (popoverTrigger) => {
if (popoverTrigger === null) {
return null;
}
return popoverTrigger.evaluate((element) => {
const key = element.dataset.popoverKey;
if (!key) {
return null;
}
return `.popover[data-popover-key="${key}"]`;
});
};
/**
* Extract the HTML content of a popover corresponding to a popover trigger
*
* @param {object} popoverTrigger the puppeteer element of the popover trigger
* @return {Promise<string>} the HTML content of the trigger
*/
const getPopoverContent = (popoverTrigger) => {
if (popoverTrigger === null) {
return null;
}
return popoverTrigger.evaluate((element) => {
const key = element.dataset.popoverKey;
if (!key) {
return null;
}
const popover = document.querySelector(`.popover[data-popover-key="${key}"]`);
return popover.innerText;
});
};
module.exports.getPopoverContent = getPopoverContent;
/**
* Extract the inner text of a popover corresponding to a popover trigger
*
* @param {object} popoverTrigger the puppeteer element of the popover trigger
* @return {Promise<string>} the content of the trigger
*/
const getPopoverInnerText = (popoverTrigger) => {
if (popoverTrigger === null) {
return null;
}
return popoverTrigger.evaluate((element) => {
const key = element.dataset.popoverKey;
if (!key) {
return null;
}
const popover = document.querySelector(`.popover[data-popover-key="${key}"]`);
return popover.innerText;
});
};
module.exports.getPopoverInnerText = getPopoverInnerText;
/**
* Check that the fist cell of the given column contains a popover displayed if the text overflows (named balloon) and that the popover's
* content is correct
*
* @param {puppeteer.Page} page the puppeteer page
* @param {number} rowIndex the index of the row to look for balloon presence
* @param {number} columnIndex the index of the column to look for balloon presence
* @returns {Promise<void>} resolve once balloon is validated
*/
module.exports.checkColumnBalloon = async (page, rowIndex, columnIndex) => {
const popoverTriggerSelector = `tbody tr:nth-of-type(${rowIndex}) td:nth-of-type(${columnIndex}) .popover-trigger`;
const popoverTrigger = await page.waitForSelector(popoverTriggerSelector);
const triggerContent = await popoverTrigger.evaluate((element) => element.querySelector('.w-wrapped').innerText);
// Puppeteer hover function sometimes do not trigger the mouseover, manually trigger it
await page.evaluate((popoverTriggerSelector) => {
const element = document.querySelector(popoverTriggerSelector);
element.dispatchEvent(new Event('mouseover', { bubbles: true }));
}, popoverTriggerSelector);
const popoverSelector = await this.getPopoverSelector(popoverTrigger);
await this.expectInnerTextTo(
page,
popoverSelector,
// Newlines may be inconsistent between balloon and original data
(popoverContent) => popoverContent.replaceAll('\n', '') === triggerContent.replaceAll('\n', ''),
);
};
/**
* Fill the input at the given selector and triggers the given events on it
*
* @param {puppeteer.Page} page the puppeteer's page object
* @param {string} inputSelector the selector of the input to fill
* @param {string} value the value to type in the input
* @param {string[]} [events=['input']] the list of events to trigger on the input after typing
* @return {Promise} resolves once the value has been typed
*/
module.exports.fillInput = async (page, inputSelector, value, events = ['input']) => {
await page.waitForSelector(inputSelector);
await page.evaluate((inputSelector, value, events) => {
const element = document.querySelector(inputSelector);
element.value = value;
for (const eventKey of events) {
element.dispatchEvent(new Event(eventKey, { bubbles: true }));
}
}, inputSelector, value, events);
};
/**
* Evaluate and return the value content of a given element handler
* @param {puppeteer.Page} page the puppeteer page
* @param {string} selector the input selector
* @returns {Promise<XPathResult>} the html content
*/
const getInputValue = async (page, selector) => {
const inputElementHandler = await page.waitForSelector(selector, { timeout: 200 });
return inputElementHandler.evaluate((input) => input.value);
};
module.exports.getInputValue = getInputValue;
/**
* Expect an element to have a given value
*
* @param {puppeteer.Page} page Puppeteer page object.
* @param {string} selector the input selector
* @param {string} value expect input value
* @return {Promise<void>} resolves once the value has been checked
*/
module.exports.expectInputValue = async (page, selector, value) => {
expect(await getInputValue(page, selector)).to.equal(value);
};
/**
* Expect the current page's URL to have exactly the given parameters (unordered)
*
* For now only handle scalar parameters
*
* @param {puppeteer.Page} page the puppeteer page
* @param {object} expectedUrlParameters the expected parameters as an object of key values
* @param {string[]} url params which are ignored when checking their value
* @return {void}
*/
module.exports.expectUrlParams = (page, expectedUrlParameters, ignoreParams = []) => {
const [, parametersExpr] = page.url().split('?');
const urlParameters = parametersExpr.split('&');
const mismatchingUrlParams = {};
for (const urlParameter of urlParameters) {
const [key, value] = urlParameter.split('=');
// Convert expected to string, if it is a number for example
if (`${expectedUrlParameters[key]}` !== value && !ignoreParams.includes(key)) {
mismatchingUrlParams[key] = {
expected: expectedUrlParameters[key],
actual: value,
};
}
}
expect(mismatchingUrlParams).to.eql({});
};
/**
* Method to check cells of columns with given id have expected innerText
*
* @param {puppeteer.Page} page the puppeteer page
* @param {string} columnId column id
* @param {string[]} [expectedInnerTextValues] values expected in columns
*
* @return {Promise<void>} resolve once column values were checked
*/
module.exports.expectColumnValues = async (page, columnId, expectedInnerTextValues) => {
try {
await page.waitForFunction(
(columnId, expectedInnerTextValues) => {
const cells = document.querySelectorAll(`table tbody .column-${columnId}`);
if (cells.length !== expectedInnerTextValues.length) {
return false;
}
for (const rowIndex in expectedInnerTextValues) {
if (cells[rowIndex].innerText !== expectedInnerTextValues[rowIndex]) {
return false;
}
}
return true;
},
{},
columnId,
expectedInnerTextValues,
);
} catch (_) {
// Use expect to have explicit error message
expect(await getColumnCellsInnerTexts(page, columnId)).to.deep.equal(expectedInnerTextValues);
}
};
/**
* Method to check cells of a row with given id have expected innerText
*
* @param {puppeteer.Page} page the puppeteer page
* @param {string} rowId row id
* @param {Object<string, string>} [expectedInnerTextValues] values expected in the row
*
* @return {Promise<void>} resolve once row's values were checked
*/
module.exports.expectRowValues = async (page, rowId, expectedInnerTextValues) => {
try {
await page.waitForFunction((rowId, expectedInnerTextValues) => {
for (const columnId in expectedInnerTextValues) {
const actualValue = document.querySelector(`table tbody tr:nth-of-type(${rowId}) .column-${columnId}`).innerText;
if (expectedInnerTextValues[columnId] !== actualValue) {
return false;
}
}
return true;
}, {}, rowId, expectedInnerTextValues);
} catch {
const rowInnerTexts = {};
for (const columnId in expectedInnerTextValues) {
rowInnerTexts[columnId] = await page.evaluate(
(rowId, columnId) => {
const column = document.querySelector(`table tbody tr:nth-of-type(${rowId}) .column-${columnId}`);
if (!column) {
throw new Error(`No element found for row ${rowId} and column ${columnId}`);
}
return column.innerText;
},
rowId,
columnId,
);
}
expect(rowInnerTexts).to.eql(expectedInnerTextValues);
}
};
/**
* Generic method to validate inner text of cells belonging column with given id.
* It checks exact match with given values
*
* @param {puppeteer.Page} page the puppeteer page
* @param {string} columnId column id
* @param {string} expectedValuesRegex string that regex constructor `RegExp(expectedValuesRegex)` returns desired regular expression
* @param {object} options options
* @param {'every'|'some'} [options.valuesCheckingMode = 'every'] whether all values are expected to match regex or at least one
* @param {boolean} [options.negation] if true it's expected not to match given regex
*
* @return {Promise<void>} resolved once column values were checked
*/
module.exports.checkColumnValuesWithRegex = async (page, columnId, expectedValuesRegex, options = {}) => {
const {
valuesCheckingMode = 'every',
negation = false,
} = options;
await page.waitForFunction((columnId, regexString, valuesCheckingMode, negation) => {
// Browser context, be careful when modifying
const names = [...document.querySelectorAll(`table tbody .column-${columnId}`)].map(({ innerText }) => innerText);
return names.length
&& names[valuesCheckingMode]((name) =>
negation ? !RegExp(regexString).test(name) : RegExp(regexString).test(name));
}, { timeout: 1500 }, columnId, expectedValuesRegex, valuesCheckingMode, negation);
};
/**
* Tests whether sorting of main table by column with given id works properly
* It is required there are a least two rows in the table
* @param {puppeteer.Page} page the puppeteer page
* @param {string} columnId subject column id
* @return {Promise<void>} resolve once table sorting was successfully checked
*/
module.exports.testTableSortingByColumn = async (page, columnId) => {
// Expect a sorting preview to appear when hovering over column header
await page.waitForSelector(`th#${columnId}`);
await page.hover(`th#${columnId}`);
await page.waitForSelector(`#${columnId}-sort-preview`);
const notOrderData = await getColumnCellsInnerTexts(page, columnId);
// Sort in ASCENDING manner
await this.pressElement(page, `th#${columnId}`, true);
this.expectColumnValues(page, columnId, [...notOrderData].sort());
// Sort in DESCENDING manner
await this.pressElement(page, `th#${columnId}`, true);
this.expectColumnValues(page, columnId, [...notOrderData].sort().reverse());
// Revoke sorting
await this.pressElement(page, `th#${columnId}`, true);
this.expectColumnValues(page, columnId, notOrderData);
};
/**
* Validate content of table body
* @param {puppeteer.Page} page the puppeteer page
* @param {Map<string, function<string, boolean>>} validators mapping of column names to cell data validator,
* each validator must return value `true` if content is ok, false otherwise
* @return {Promise<void>} resolve once data was successfully validated
*/
module.exports.validateTableData = async (page, validators) => {
await page.waitForSelector('table tbody');
for (const [columnId, validator] of validators) {
const columnData = await getColumnCellsInnerTexts(page, columnId);
expect(columnData, `Too few values for column ${columnId} or there is no such column`).to.be.length.greaterThan(0);
expect(
columnData.every((cellData) => validator(cellData)),
`Invalid data in column ${columnId}: (${columnData})`,
).to.be.true;
}
};
/**
* Listener accepting browser confirmation dialog
* @param {page.dialog} dialog dialog
* @return {void}
*/
const acceptDialogEventListener = (dialog) => dialog.accept();
/**
* Listener dismissing browser confirmation dialog
* @param {page.dialog} dialog dialog
* @return {void}
*/
const dismissDialogEventListener = (dialog) => dialog.dismiss();
/**
* Set listener on dialog event to accept it
* @param {puppeteer.page} page page handler
* @return {void}
*/
module.exports.setConfirmationDialogToBeAccepted = (page) => {
page.off('dialog', dismissDialogEventListener);
page.on('dialog', acceptDialogEventListener);
};
/**
* Set listener on dialog event to dismiss it
* @param {puppeteer.page} page page handler
* @return {void}
*/
module.exports.setConfirmationDialogToBeDismissed = (page) => {
page.off('dialog', acceptDialogEventListener);
page.on('dialog', dismissDialogEventListener);
};
/**
* Unset accept and dismiss listeners off dialog event
* @param {puppeteer.page} page page handler
* @return {void}
*/
module.exports.unsetConfirmationDialogActions = (page) => {
page.off('dialog', dismissDialogEventListener);
page.off('dialog', acceptDialogEventListener);
};
/**
* Expect a link to have a given text and href
* @param {puppeteer.Page|puppeteer.ElementHandle} element Puppeteer element or page object.
* @param {string} selector css selector.
* @param {string} [expected.href] expected href of the link
* @param {string} [expected.innerText] expected inner text of the link
* @return {Promise<void>} promise
*/
module.exports.expectLink = async (element, selector, { href, innerText }) => {
await element.waitForSelector(selector);
const actualLinkProperties = await (await element.$(selector)).evaluate(({ innerText, href }) => ({ href, innerText }));
expect(actualLinkProperties).to.eql({ href, innerText });
};
/**
* Validate date string against given format
* @param {string} date date (time) string
* @param {string} [format = 'DD/MM/YYYY hh:mm:ss'] format to validate against
* @return {boolean} true if format is correct, false otherwise
*/
module.exports.validateDate = (date, format = 'DD/MM/YYYY hh:mm:ss') => !isNaN(dateAndTime.parse(date, format));
/**
* Return the selector for all the inputs composing a period inputs
*
* @param {string} popoverSelector the selector of the period inputs parent
* @return {{fromDateSelector: string, fromTimeSelector: string, toDateSelector: string, toTimeSelector: string}} the selectors
*/
module.exports.getPeriodInputsSelectors = (popoverSelector) => {
const commonInputsAncestor = `${popoverSelector} > div > div > div > div`;
return {
fromDateSelector: `${commonInputsAncestor} > div:nth-child(1) input:nth-child(1)`,
fromTimeSelector: `${commonInputsAncestor} > div:nth-child(1) input:nth-child(2)`,
toDateSelector: `${commonInputsAncestor} > div:nth-child(2) input:nth-child(1)`,
toTimeSelector: `${commonInputsAncestor} > div:nth-child(2) input:nth-child(2)`,
};
};