webship-js 2.0.11 → 2.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.circleci/config.yml +10 -1
- package/.drone.yml +7 -7
- package/.github/workflows/github-actions.yml +48 -0
- package/.gitlab-ci.yml +9 -4
- package/.harness/webship-js-pipeline.yml +5 -6
- package/.semaphore/semaphore.yml +6 -9
- package/.teamcity/settings.kts +7 -6
- package/.travis.yml +6 -1
- package/AGENTS.md +1 -1
- package/CLAUDE.md +65 -23
- package/Jenkinsfile +5 -3
- package/azure-pipelines.yml +17 -8
- package/bamboo-specs/bamboo.yml +9 -15
- package/bin/init-webship.js +53 -10
- package/bitbucket-pipelines.yml +5 -1
- package/buildspec.yml +6 -7
- package/cloudbuild.yaml +28 -12
- package/codefresh.yml +6 -6
- package/cucumber.js +17 -10
- package/docs/00-quick-start.md +8 -0
- package/docs/02-bbr-smart-waits.md +15 -10
- package/docs/03-selector-registry.md +24 -0
- package/docs/04-step-reference.md +51 -25
- package/docs/05-web-first-assertions.md +6 -0
- package/docs/07-auth-state.md +1 -1
- package/docs/08-clock-mocking.md +21 -2
- package/docs/09-api-testing.md +40 -2
- package/docs/10-accessibility.md +2 -0
- package/docs/11-debugging.md +3 -1
- package/docs/12-ai-agent-guide.md +5 -0
- package/docs/13-faq.md +72 -1
- package/docs/14-recipes-cookbook.md +2 -0
- package/docs/15-tag-conventions.md +2 -1
- package/docs/16-ci-cd.md +140 -119
- package/docs/README.md +5 -5
- package/docs/advanced-screenshots.md +3 -1
- package/docs/api-step-definitions.md +16 -2
- package/docs/global-settings.md +69 -17
- package/docs/install-webship-js.md +2 -0
- package/docs/step-definitions/then-i-should-see.md +14 -1
- package/docs/step-definitions/then-item-checkbox.md +2 -0
- package/docs/step-definitions/when-i-fill.md +4 -0
- package/docs/step-definitions/when-i-select-option-select-list.md +2 -0
- package/examples/check-switch.html +37 -0
- package/examples/choice-controls.html +29 -0
- package/examples/click-whitespace.html +37 -0
- package/examples/datetime-fields.html +52 -0
- package/examples/element-selector-hint.html +16 -0
- package/examples/field-states.html +27 -0
- package/examples/fill-in-empty.html +26 -0
- package/examples/fill-unreachable.html +27 -0
- package/examples/follow-hidden-first.html +29 -0
- package/examples/iframe-inner.html +20 -0
- package/examples/iframe-nested.html +16 -0
- package/examples/iframe-outer.html +15 -0
- package/examples/multi-value-fields.html +54 -0
- package/examples/registered-names.html +15 -0
- package/examples/select-by-label.html +33 -0
- package/examples/settle-budget.html +21 -0
- package/examples/sorted-tables.html +38 -0
- package/examples/text-matching.html +48 -0
- package/examples/text-order.html +25 -0
- package/examples/touch.html +22 -0
- package/examples/viewport-top.html +36 -0
- package/package.json +17 -1
- package/playwright.config.ts +3 -1
- package/tests/check-api-launch-url.js +106 -0
- package/tests/check-assets.js +103 -0
- package/tests/check-attachments.js +105 -0
- package/tests/check-breakpoints.js +117 -0
- package/tests/check-clock.js +143 -0
- package/tests/check-config.js +90 -0
- package/tests/check-context.js +215 -0
- package/tests/check-dry-run.js +104 -0
- package/tests/check-examples.js +10 -4
- package/tests/check-exit-report.js +141 -0
- package/tests/check-javascript-errors.js +105 -0
- package/tests/check-must-fail.js +5 -4
- package/tests/check-network-changed.js +137 -0
- package/tests/check-scaffold.js +54 -2
- package/tests/check-screenshots.js +117 -0
- package/tests/check-settle-verbs.js +137 -0
- package/tests/check-time-limit.js +104 -0
- package/tests/check-video.js +156 -0
- package/tests/check-world.js +167 -0
- package/tests/features/api-base-url.feature +25 -0
- package/tests/features/api-form-data.feature +18 -0
- package/tests/features/api-json-paths.feature +24 -0
- package/tests/features/api-response-contains.feature +21 -0
- package/tests/features/api-response-header-presence.feature +17 -0
- package/tests/features/api-response-header.feature +17 -0
- package/tests/features/api-saved-placeholders.feature +37 -0
- package/tests/features/api-step-definitions-individual.feature +1 -1
- package/tests/features/api-tables.feature +40 -0
- package/tests/features/breakpoints.feature +25 -0
- package/tests/features/check-switch.feature +28 -0
- package/tests/features/choice-controls.feature +35 -0
- package/tests/features/click-whitespace.feature +29 -0
- package/tests/features/complete-api-testing-examples.feature +1 -1
- package/tests/features/datetime-field-lookup.feature +29 -0
- package/tests/features/element-selector-hint.feature +14 -0
- package/tests/features/field-state.feature +21 -0
- package/tests/features/fill-in-empty-value.feature +41 -0
- package/tests/features/fill-reachable.feature +13 -0
- package/tests/features/follow-hidden-first.feature +9 -0
- package/tests/features/iframe-nested.feature +43 -0
- package/tests/features/javascript-tolerated-errors.feature +20 -0
- package/tests/features/modal-open.feature +13 -0
- package/tests/features/multi-value-field-lookup.feature +30 -0
- package/tests/features/registered-names.feature +14 -0
- package/tests/features/select-by-label.feature +31 -0
- package/tests/features/selector-files.feature +14 -0
- package/tests/features/selectors-table-header.feature +35 -0
- package/tests/features/settle-budget.feature +11 -0
- package/tests/features/sorted-tables.feature +19 -0
- package/tests/features/storage-quoted-values.feature +26 -0
- package/tests/features/text-matching.feature +38 -0
- package/tests/features/text-order.feature +14 -0
- package/tests/features/touch.feature +21 -0
- package/tests/features/viewport-top.feature +13 -0
- package/tests/features/xml-namespaces.feature +34 -0
- package/tests/must-fail/api-json-paths.feature +21 -0
- package/tests/must-fail/api-response-contains.feature +23 -0
- package/tests/must-fail/api-response-header-presence.feature +17 -0
- package/tests/must-fail/api-response-header.feature +21 -0
- package/tests/must-fail/api-without-base-url.feature +11 -0
- package/tests/must-fail/breakpoints.feature +15 -0
- package/tests/must-fail/choice-controls.feature +25 -0
- package/tests/must-fail/clock.feature +11 -0
- package/tests/must-fail/datetime-field.feature +10 -0
- package/tests/must-fail/element-selector-hint.feature +17 -0
- package/tests/must-fail/field-state.feature +20 -0
- package/tests/must-fail/fill-field.feature +30 -0
- package/tests/must-fail/iframe-text.feature +17 -0
- package/tests/must-fail/modal-open.feature +26 -0
- package/tests/must-fail/multi-value-field.feature +18 -0
- package/tests/must-fail/registered-names.feature +25 -0
- package/tests/must-fail/select-list.feature +15 -0
- package/tests/must-fail/selector-files.feature +10 -0
- package/tests/must-fail/sorted-tables.feature +20 -0
- package/tests/must-fail/storage-before-a-page.feature +13 -0
- package/tests/must-fail/text-matching.feature +16 -0
- package/tests/must-fail/text-order.feature +15 -0
- package/tests/must-fail/viewport-top.feature +20 -0
- package/tests/must-fail/yaml-numbers.feature +48 -0
- package/tests/step-definitions/a11y.steps.js +24 -15
- package/tests/step-definitions/action.steps.js +53 -20
- package/tests/step-definitions/api.steps.js +349 -67
- package/tests/step-definitions/assertion.steps.js +100 -10
- package/tests/step-definitions/auth.steps.js +15 -18
- package/tests/step-definitions/clock.steps.js +22 -0
- package/tests/step-definitions/debug.steps.js +8 -0
- package/tests/step-definitions/dialog.steps.js +7 -0
- package/tests/step-definitions/element.steps.js +132 -17
- package/tests/step-definitions/field.steps.js +412 -96
- package/tests/step-definitions/form.steps.js +88 -37
- package/tests/step-definitions/iframe.steps.js +89 -29
- package/tests/step-definitions/input.steps.js +26 -7
- package/tests/step-definitions/javascript.steps.js +64 -22
- package/tests/step-definitions/modal.steps.js +79 -13
- package/tests/step-definitions/navigation.steps.js +14 -0
- package/tests/step-definitions/network.steps.js +15 -5
- package/tests/step-definitions/response.steps.js +6 -4
- package/tests/step-definitions/responsive.steps.js +26 -33
- package/tests/step-definitions/screenshot.steps.js +25 -8
- package/tests/step-definitions/scroll.steps.js +20 -0
- package/tests/step-definitions/selectors.steps.js +95 -48
- package/tests/step-definitions/storage.steps.js +38 -13
- package/tests/step-definitions/table.steps.js +81 -6
- package/tests/step-definitions/video.steps.js +52 -55
- package/tests/step-definitions/wait.steps.js +88 -23
- package/tests/step-definitions/web-first.steps.js +69 -35
- package/tests/step-definitions/webship.js +741 -145
- package/tests/step-definitions/xml.steps.js +49 -15
- package/tests/step-definitions/yaml.steps.js +45 -20
|
@@ -4,22 +4,42 @@ const { setWorldConstructor, World, Before, After, BeforeStep, AfterStep, setDef
|
|
|
4
4
|
const playwright = require('playwright');
|
|
5
5
|
const playwrightConfig = require(require('path').join(process.cwd(), 'playwright.config'));
|
|
6
6
|
const path = require('path');
|
|
7
|
+
const fs = require('fs');
|
|
7
8
|
|
|
8
9
|
// ---------------------------------------------------------------------------
|
|
9
10
|
// Output filter — strip noisy `✔ Before # ...` / `✔ After # ...` hook lines
|
|
10
11
|
// from cucumber-js's failure dump so tester-facing output stays focused on
|
|
11
|
-
// the failing step + hint.
|
|
12
|
+
// the failing step + hint. In a dry run (--dry-run or -d), also strip the
|
|
13
|
+
// pretty formatter's "- skipped" lines: every hook and every step of a dry
|
|
14
|
+
// run is skipped, and a line for each buries the "? undefined" and
|
|
15
|
+
// "✖ ambiguous" lines the dry run is for. Disable with
|
|
16
|
+
// WEBSHIP_FILTER_HOOK_LINES=off.
|
|
12
17
|
// ---------------------------------------------------------------------------
|
|
13
18
|
if (process.env.WEBSHIP_FILTER_HOOK_LINES !== 'off') {
|
|
14
19
|
const HOOK_LINE = /^\s*[✔✖✗⚠?-]\s+(?:Before|After|BeforeStep|AfterStep)\b.*$/;
|
|
20
|
+
const DRY_RUN = process.argv.slice(2).some((arg) => arg === '--dry-run' || arg === '-d');
|
|
21
|
+
const SKIPPED_LINE = /^\s*-\s+skipped\s*$/;
|
|
22
|
+
const plain = (line) => line.replace(/\x1b\[[0-9;]*m/g, '');
|
|
23
|
+
const dropped = (line) => HOOK_LINE.test(plain(line)) || (DRY_RUN && SKIPPED_LINE.test(plain(line)));
|
|
15
24
|
const wrap = (stream) => {
|
|
16
25
|
const orig = stream.write.bind(stream);
|
|
26
|
+
// The pretty formatter writes a line and its line break in two writes:
|
|
27
|
+
// when a line is dropped, so is the line break that follows it.
|
|
28
|
+
let dropLineBreak = false;
|
|
17
29
|
stream.write = (chunk, encoding, cb) => {
|
|
18
30
|
if (typeof chunk === 'string' || Buffer.isBuffer(chunk)) {
|
|
19
31
|
const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
|
|
32
|
+
const skipBreak = dropLineBreak && /^\r?\n$/.test(text);
|
|
33
|
+
dropLineBreak = false;
|
|
34
|
+
if (skipBreak || (!text.includes('\n') && text.trim() && dropped(text))) {
|
|
35
|
+
dropLineBreak = !skipBreak;
|
|
36
|
+
const done = typeof encoding === 'function' ? encoding : cb;
|
|
37
|
+
if (typeof done === 'function') process.nextTick(done);
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
20
40
|
const filtered = text
|
|
21
41
|
.split('\n')
|
|
22
|
-
.filter((line) => !
|
|
42
|
+
.filter((line) => !dropped(line))
|
|
23
43
|
.join('\n');
|
|
24
44
|
return orig(filtered, encoding, cb);
|
|
25
45
|
}
|
|
@@ -117,11 +137,14 @@ async function pollPage(page, probe, arg, timeout, interval) {
|
|
|
117
137
|
* Wait for the page to reach an "edge" of activity — DOM ready, network
|
|
118
138
|
* idle, no pending AJAX or timers, and no DOM mutations for ≥250 ms.
|
|
119
139
|
*
|
|
120
|
-
* Each stage gets a share of the budget rather than "whatever
|
|
121
|
-
* stage that can never resolve cannot starve the ones after
|
|
122
|
-
* analytics, a chat widget or a self-rescheduling timer,
|
|
123
|
-
* arrives; capping it at half the budget keeps the AJAX /
|
|
124
|
-
* DOM-quiet probe — the useful one — running.
|
|
140
|
+
* Each stage but the last gets a share of the budget rather than "whatever
|
|
141
|
+
* is left", so a stage that can never resolve cannot starve the ones after
|
|
142
|
+
* it. On a page with analytics, a chat widget or a self-rescheduling timer,
|
|
143
|
+
* `networkidle` never arrives; capping it at half the budget keeps the AJAX /
|
|
144
|
+
* pending-timer / DOM-quiet probe — the useful one — running. That probe is
|
|
145
|
+
* the last stage, with nothing after it to starve: it gets everything the
|
|
146
|
+
* earlier stages left, so a request or a timer of more than half the budget
|
|
147
|
+
* is still waited for.
|
|
125
148
|
*
|
|
126
149
|
* Returns within `timeout` ms even when nothing on the page ever settles.
|
|
127
150
|
*
|
|
@@ -151,15 +174,19 @@ async function smartSettle(page, timeout) {
|
|
|
151
174
|
if (!await stage(0.25, (t) => page.waitForSelector('body', { state: 'attached', timeout: t }))) return;
|
|
152
175
|
if (!await stage(0.25, (t) => page.waitForLoadState('domcontentloaded', { timeout: t }))) return;
|
|
153
176
|
if (!await stage(0.5, (t) => page.waitForLoadState('networkidle', { timeout: t }))) return;
|
|
154
|
-
await stage(
|
|
177
|
+
await stage(1, (t) => pollPage(
|
|
155
178
|
page,
|
|
156
179
|
(quietMs) => {
|
|
157
180
|
const ajax = window.__webshipAjaxCount;
|
|
158
181
|
const timers = window.__webshipPendingTimers;
|
|
159
182
|
const last = window.__webshipLastMutation;
|
|
183
|
+
const now = typeof window.__webshipNow === 'function' ? window.__webshipNow() : Date.now();
|
|
184
|
+
// Under a fake clock the page's timers are the clock's and run only
|
|
185
|
+
// when it moves; the ones the probes count are the clock's own.
|
|
186
|
+
const fakeClock = !!(window.Date && window.Date.isFake);
|
|
160
187
|
if (typeof ajax === 'number' && ajax > 0) return false;
|
|
161
|
-
if (typeof timers === 'number' && timers > 0) return false;
|
|
162
|
-
if (typeof last === 'number' &&
|
|
188
|
+
if (!fakeClock && typeof timers === 'number' && timers > 0) return false;
|
|
189
|
+
if (typeof last === 'number' && now - last < quietMs) return false;
|
|
163
190
|
return true;
|
|
164
191
|
},
|
|
165
192
|
250,
|
|
@@ -412,7 +439,9 @@ async function sendRequest(world, { method, url, headers, data, session }) {
|
|
|
412
439
|
|
|
413
440
|
/**
|
|
414
441
|
* Navigate to a URL with friendly error messages for common failures
|
|
415
|
-
* (server down, DNS, empty response).
|
|
442
|
+
* (server down, DNS, empty response). A load that Chromium aborts with
|
|
443
|
+
* net::ERR_NETWORK_CHANGED (the network of the machine changed under it) is
|
|
444
|
+
* tried once more, with a line in the log. All other errors rethrow with
|
|
416
445
|
* preserved stack + extra context.
|
|
417
446
|
*
|
|
418
447
|
* @param {import('playwright').Page} page
|
|
@@ -421,7 +450,18 @@ async function sendRequest(world, { method, url, headers, data, session }) {
|
|
|
421
450
|
*/
|
|
422
451
|
async function gotoUrl(page, url) {
|
|
423
452
|
try {
|
|
424
|
-
|
|
453
|
+
try {
|
|
454
|
+
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
455
|
+
} catch (e) {
|
|
456
|
+
// Chromium aborts every request in flight when the network of the
|
|
457
|
+
// machine changes: a Docker network created or removed, as when another
|
|
458
|
+
// DDEV project starts or stops on the same machine. The page load then
|
|
459
|
+
// fails with net::ERR_NETWORK_CHANGED although the site is fine. It is
|
|
460
|
+
// loaded once more, and the run says so; nothing else is retried.
|
|
461
|
+
if (!/net::ERR_NETWORK_CHANGED/.test(String((e && e.message) || ''))) throw e;
|
|
462
|
+
console.warn(`[webship-js] Loading "${url}" was aborted because the network of this machine changed (net::ERR_NETWORK_CHANGED, as when a Docker network starts or stops); loading it once more.`);
|
|
463
|
+
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
464
|
+
}
|
|
425
465
|
} catch (e) {
|
|
426
466
|
const msg = e.message || '';
|
|
427
467
|
// Empty response: harmless, swallow.
|
|
@@ -454,31 +494,75 @@ async function gotoUrl(page, url) {
|
|
|
454
494
|
*
|
|
455
495
|
* @param {import('playwright').Page} page
|
|
456
496
|
* @param {string} field - Label / placeholder / name.
|
|
457
|
-
* @param {string} value - Value to type.
|
|
497
|
+
* @param {string} value - Value to type; null or undefined fills an empty value.
|
|
498
|
+
* @param {WebshipWorld} [world] - The World of the step, to tell a name of the selector registry.
|
|
458
499
|
* @returns {Promise<void>}
|
|
459
500
|
*/
|
|
460
|
-
async function fillField(page, field, value) {
|
|
501
|
+
async function fillField(page, field, value, world) {
|
|
502
|
+
// An empty value in a step ("") reaches the definition as null: it means "".
|
|
503
|
+
value = value === undefined || value === null ? '' : String(value);
|
|
461
504
|
const byLabel = page.getByLabel(field, { exact: true });
|
|
462
505
|
if (await byLabel.count() > 0) {
|
|
463
|
-
await byLabel
|
|
506
|
+
await fillLocator(page, byLabel, value, field);
|
|
464
507
|
return;
|
|
465
508
|
}
|
|
466
509
|
const byPlaceholder = page.getByPlaceholder(field, { exact: true });
|
|
467
510
|
if (await byPlaceholder.count() > 0) {
|
|
468
|
-
await byPlaceholder
|
|
511
|
+
await fillLocator(page, byPlaceholder, value, field);
|
|
469
512
|
return;
|
|
470
513
|
}
|
|
471
514
|
const byName = page.locator(`[name="${field}"]`).first();
|
|
472
515
|
if (await byName.count() > 0) {
|
|
473
|
-
await byName
|
|
516
|
+
await fillLocator(page, byName, value, field);
|
|
474
517
|
return;
|
|
475
518
|
}
|
|
476
|
-
throw
|
|
477
|
-
`
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
519
|
+
throw failure(page, `Could not find a field for "${field}".`, {
|
|
520
|
+
hint: registeredNameHint(world, field, { withSelector: (selector) => `I fill in the field "${selector}" with "${value}"` }) ||
|
|
521
|
+
`the step looks for a field whose label, placeholder or name is exactly "${field}", letter case included. For an id, a class or another attribute, use: I fill in "${field}" with "${value}" by attr`,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Fill the field a step found. A field that is hidden, disabled or read-only,
|
|
527
|
+
* or that is not on the page, fails the step within 5 seconds with what is
|
|
528
|
+
* wrong with it, the page and a hint, instead of Playwright's raw timeout.
|
|
529
|
+
*
|
|
530
|
+
* @param {import('playwright').Page} page
|
|
531
|
+
* @param {import('playwright').Locator} loc - The field.
|
|
532
|
+
* @param {string} value - Value to type; null or undefined fills an empty value.
|
|
533
|
+
* @param {string} name - How the step named the field, for the message.
|
|
534
|
+
* @returns {Promise<void>}
|
|
535
|
+
*/
|
|
536
|
+
async function fillLocator(page, loc, value, name) {
|
|
537
|
+
const text = value === undefined || value === null ? '' : String(value);
|
|
538
|
+
try {
|
|
539
|
+
await loc.fill(text, { timeout: 5000 });
|
|
540
|
+
return;
|
|
541
|
+
} catch (e) {
|
|
542
|
+
let state = '';
|
|
543
|
+
try {
|
|
544
|
+
if (await loc.count() === 0) state = 'missing';
|
|
545
|
+
else if (!(await loc.first().isVisible())) state = 'hidden';
|
|
546
|
+
else if (await loc.first().isDisabled({ timeout: 1000 })) state = 'disabled';
|
|
547
|
+
else if (!(await loc.first().isEditable({ timeout: 1000 }))) state = 'read-only';
|
|
548
|
+
} catch { /* the page changed while it was looked at */ }
|
|
549
|
+
if (state === 'missing') {
|
|
550
|
+
throw failure(page, `No field with "${name}" was found after 5 seconds.`, {
|
|
551
|
+
hint: 'by attribute the step reads the text as the attribute it names, else as an id, a class, a name, a test id, an aria-label, a value, a placeholder or a title; a text that starts with #, . or [ is a CSS selector.',
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
if (state === 'hidden') {
|
|
555
|
+
throw failure(page, `The field "${name}" is on the page but hidden, so it cannot be filled.`, {
|
|
556
|
+
hint: 'a field that shows after an action can be filled once it is visible: wait for it first. A field hidden behind a rich-text editor is filled with: I fill in the WYSIWYG field "<name>" with the "<text>"',
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
if (state === 'disabled' || state === 'read-only') {
|
|
560
|
+
throw failure(page, `The field "${name}" is ${state}, so it cannot be filled.`, {
|
|
561
|
+
hint: `a ${state} field keeps its value; to check it, use: the field "${name}" should have "${state}" state`,
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
throw failure(page, `Could not fill the field "${name}".`, { hint: `${humanize(e)}.` });
|
|
565
|
+
}
|
|
482
566
|
}
|
|
483
567
|
|
|
484
568
|
/**
|
|
@@ -523,6 +607,40 @@ async function locateByLabelOrSelector(page, name, timeout) {
|
|
|
523
607
|
}
|
|
524
608
|
}
|
|
525
609
|
|
|
610
|
+
// The package's own tests/assets/: read last, so that a file only the package
|
|
611
|
+
// ships keeps working.
|
|
612
|
+
const PACKAGE_ASSETS = path.join(__dirname, '..', 'assets');
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Find a file a step names by its name: an absolute path as written; a
|
|
616
|
+
* relative one in the World's `assetsFolder` (the project's tests/assets/),
|
|
617
|
+
* then as written from the project root, then in the package's own
|
|
618
|
+
* tests/assets/. Fails plainly, with the paths tried, when none holds it.
|
|
619
|
+
*
|
|
620
|
+
* @param {WebshipWorld} world
|
|
621
|
+
* @param {string} name - The file as the step gives it.
|
|
622
|
+
* @returns {string} The absolute path of the file.
|
|
623
|
+
*/
|
|
624
|
+
function resolveAssetFile(world, name) {
|
|
625
|
+
const fs = require('fs');
|
|
626
|
+
const file = String(name === undefined || name === null ? '' : name).trim();
|
|
627
|
+
const tried = path.isAbsolute(file)
|
|
628
|
+
? [file]
|
|
629
|
+
: [...new Set([
|
|
630
|
+
path.resolve((world && world.assetsFolder) || path.join(process.cwd(), 'tests', 'assets'), file),
|
|
631
|
+
path.resolve(process.cwd(), file),
|
|
632
|
+
path.resolve(PACKAGE_ASSETS, file),
|
|
633
|
+
])];
|
|
634
|
+
const found = tried.find((candidate) => {
|
|
635
|
+
try { return fs.statSync(candidate).isFile(); } catch { return false; }
|
|
636
|
+
});
|
|
637
|
+
if (found) return found;
|
|
638
|
+
throw failure(world && world.page, `The file "${file}" was not found.`, {
|
|
639
|
+
found: `nothing at ${tried.map((candidate) => path.relative(process.cwd(), candidate) || candidate).join(', ')}`,
|
|
640
|
+
hint: 'put the file in the tests/assets/ folder of the project, or name it by its path from the project root.',
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
|
|
526
644
|
/**
|
|
527
645
|
* Left-pad a number with zeros to the requested width.
|
|
528
646
|
*
|
|
@@ -761,6 +879,55 @@ function excerpt(text, max) {
|
|
|
761
879
|
return clean.length > limit ? clean.slice(0, limit) + '…' : clean;
|
|
762
880
|
}
|
|
763
881
|
|
|
882
|
+
/**
|
|
883
|
+
* Locator for the page when its text contains `text`, read the way the page
|
|
884
|
+
* text steps (`I should see`, `I should not see`, `eventually I should see`)
|
|
885
|
+
* read it: Playwright's text matching on `<body>`, letter case ignored, white
|
|
886
|
+
* space collapsed, the text of hidden elements included, the text of
|
|
887
|
+
* `<script>`, `<noscript>` and `<style>` left out. It matches nothing while
|
|
888
|
+
* the text is not on the page, so `waitFor({ state: 'attached' })` waits for
|
|
889
|
+
* the text to come and `waitFor({ state: 'detached' })` for it to go.
|
|
890
|
+
*
|
|
891
|
+
* @param {import('playwright').Page} page
|
|
892
|
+
* @param {string} text
|
|
893
|
+
* @returns {import('playwright').Locator}
|
|
894
|
+
*/
|
|
895
|
+
function pageTextLocator(page, text) {
|
|
896
|
+
return page.locator('body').filter({ hasText: text === undefined || text === null ? '' : String(text) });
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* The hint for a step that was given a name of the named-selector registry
|
|
901
|
+
* where it reads a text, a label or a CSS selector: it does not read the
|
|
902
|
+
* registry, so the name matched nothing. Names the bare-name step that reads
|
|
903
|
+
* it, when there is one and the name fits it, and the same step with the
|
|
904
|
+
* selector the name stands for. An empty string when `name` is not a
|
|
905
|
+
* registered name, so a failure that has nothing to do with the registry
|
|
906
|
+
* reads as before.
|
|
907
|
+
*
|
|
908
|
+
* @param {WebshipWorld} world
|
|
909
|
+
* @param {string} name - The argument the step was given.
|
|
910
|
+
* @param {Object} [forms]
|
|
911
|
+
* @param {string} [forms.bare] - The bare-name step, "{name}" for the name.
|
|
912
|
+
* @param {function(string): string} [forms.withSelector] - The step to use with the selector.
|
|
913
|
+
* @returns {string}
|
|
914
|
+
*/
|
|
915
|
+
function registeredNameHint(world, name, forms) {
|
|
916
|
+
const key = String(name === undefined || name === null ? '' : name).trim();
|
|
917
|
+
if (!key || !world) return '';
|
|
918
|
+
const css = world.__selectorsCss || {};
|
|
919
|
+
const xpath = world.__selectorsXpath || {};
|
|
920
|
+
let selector = null;
|
|
921
|
+
if (Object.prototype.hasOwnProperty.call(css, key)) selector = css[key];
|
|
922
|
+
else if (Object.prototype.hasOwnProperty.call(xpath, key)) selector = xpath[key].startsWith('xpath=') ? xpath[key] : `xpath=${xpath[key]}`;
|
|
923
|
+
if (!selector) return '';
|
|
924
|
+
const uses = [];
|
|
925
|
+
if (forms && forms.bare && /^[a-zA-Z0-9 ,-]+$/.test(key)) uses.push(forms.bare.replace('{name}', key));
|
|
926
|
+
if (forms && typeof forms.withSelector === 'function') uses.push(forms.withSelector(selector));
|
|
927
|
+
return `"${key}" is a name of the selector registry (${selector}), but this step does not read the registry.` +
|
|
928
|
+
(uses.length ? ` Use: ${uses.join(', or: ')}` : '');
|
|
929
|
+
}
|
|
930
|
+
|
|
764
931
|
/**
|
|
765
932
|
* True when an error is Playwright giving up after its timeout, which in an
|
|
766
933
|
* assertion means "what was looked for is not there".
|
|
@@ -772,6 +939,50 @@ function isTimeout(error) {
|
|
|
772
939
|
return !!error && (error.name === 'TimeoutError' || /Timeout \d+ms exceeded/.test(String(error.message || '')));
|
|
773
940
|
}
|
|
774
941
|
|
|
942
|
+
/**
|
|
943
|
+
* Check or uncheck a checkbox, or select a radio button, the way a person
|
|
944
|
+
* does. A toggle switch draws its slider over the checkbox (an invisible
|
|
945
|
+
* input under a part of its own label), and a custom checkbox hides the input
|
|
946
|
+
* and draws the box with its label: Playwright's check() then finds no way to
|
|
947
|
+
* click the input and waits out its whole timeout. A person clicks the label,
|
|
948
|
+
* and so does this when the input is hidden or covered by a part of its own
|
|
949
|
+
* label; the control must then reach the asked state. Any other control is
|
|
950
|
+
* checked by Playwright as before.
|
|
951
|
+
*
|
|
952
|
+
* @param {import('playwright').Locator} loc - The input (one element).
|
|
953
|
+
* @param {boolean} wanted - true to check / select, false to uncheck.
|
|
954
|
+
* @param {Object} [options]
|
|
955
|
+
* @param {number} [options.timeout] - For Playwright's check() / uncheck().
|
|
956
|
+
* @returns {Promise<void>}
|
|
957
|
+
*/
|
|
958
|
+
async function setChecked(loc, wanted, options) {
|
|
959
|
+
const timeout = options && options.timeout;
|
|
960
|
+
await loc.waitFor({ state: 'attached', timeout });
|
|
961
|
+
const label = (await loc.evaluateHandle((el) => {
|
|
962
|
+
const own = (el.labels && el.labels[0]) || el.closest('label');
|
|
963
|
+
if (!own) return null;
|
|
964
|
+
const style = getComputedStyle(el);
|
|
965
|
+
const box = el.getBoundingClientRect();
|
|
966
|
+
if (box.width === 0 || box.height === 0 || style.display === 'none' || style.visibility === 'hidden') return own;
|
|
967
|
+
el.scrollIntoView({ block: 'center', inline: 'center' });
|
|
968
|
+
const at = el.getBoundingClientRect();
|
|
969
|
+
const top = document.elementFromPoint(at.left + at.width / 2, at.top + at.height / 2);
|
|
970
|
+
return top && top !== el && !el.contains(top) && own.contains(top) ? own : null;
|
|
971
|
+
})).asElement();
|
|
972
|
+
if (!label) {
|
|
973
|
+
await (wanted ? loc.check({ timeout }) : loc.uncheck({ timeout }));
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
if ((await loc.isChecked()) !== wanted) await label.click({ timeout });
|
|
977
|
+
const deadline = Date.now() + 5000;
|
|
978
|
+
while ((await loc.isChecked()) !== wanted) {
|
|
979
|
+
if (Date.now() > deadline) {
|
|
980
|
+
throw new Error(`clicking its label left it ${wanted ? 'unchecked' : 'checked'}`);
|
|
981
|
+
}
|
|
982
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
775
986
|
/**
|
|
776
987
|
* Build the failure of an assertion for a tester: what was looked for, what
|
|
777
988
|
* was found, the address of the page and a hint. No call log, no stack.
|
|
@@ -808,8 +1019,10 @@ module.exports = {
|
|
|
808
1019
|
resolveUrl,
|
|
809
1020
|
sendRequest,
|
|
810
1021
|
fillField,
|
|
1022
|
+
fillLocator,
|
|
811
1023
|
getLocatorText,
|
|
812
1024
|
locateByLabelOrSelector,
|
|
1025
|
+
resolveAssetFile,
|
|
813
1026
|
pad,
|
|
814
1027
|
resolveRelativeDate,
|
|
815
1028
|
parseRelativeOffset,
|
|
@@ -819,21 +1032,133 @@ module.exports = {
|
|
|
819
1032
|
failure,
|
|
820
1033
|
excerpt,
|
|
821
1034
|
isTimeout,
|
|
1035
|
+
setChecked,
|
|
1036
|
+
registeredNameHint,
|
|
1037
|
+
pageTextLocator,
|
|
1038
|
+
breakpoints,
|
|
1039
|
+
breakpoint,
|
|
1040
|
+
onNewPage,
|
|
1041
|
+
videoFileName,
|
|
822
1042
|
};
|
|
823
1043
|
|
|
824
1044
|
// ---------------------------------------------------------------------------
|
|
825
1045
|
// Auto HTML report on cucumber-js process exit.
|
|
826
1046
|
// Disable: WEBSHIP_REPORT_DISABLE=1. Extra flags: WEBSHIP_REPORT_ARGS="--theme hierarchy --layout 2".
|
|
827
|
-
// Registered once per process
|
|
1047
|
+
// Registered once per process, and run only in the process that runs
|
|
1048
|
+
// cucumber-js: the workers of a --parallel run load these files too, but exit
|
|
1049
|
+
// before the JSON report is complete.
|
|
828
1050
|
// ---------------------------------------------------------------------------
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* The values given to an option on a command line, in order: `--name value`,
|
|
1054
|
+
* `--name=value` and the short form `-n value`.
|
|
1055
|
+
*
|
|
1056
|
+
* @param {string[]} args
|
|
1057
|
+
* @param {string} name - Long name, with its dashes (`--format`).
|
|
1058
|
+
* @param {string} [short] - Short name, with its dash (`-f`).
|
|
1059
|
+
* @returns {string[]}
|
|
1060
|
+
*/
|
|
1061
|
+
function optionValues(args, name, short) {
|
|
1062
|
+
const values = [];
|
|
1063
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
1064
|
+
if (args[i] === name || (short && args[i] === short)) {
|
|
1065
|
+
if (i + 1 < args.length) values.push(args[i + 1]);
|
|
1066
|
+
i += 1;
|
|
1067
|
+
} else if (args[i].startsWith(name + '=')) {
|
|
1068
|
+
values.push(args[i].slice(name.length + 1));
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
return values;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
/**
|
|
1075
|
+
* The file of the last `json` formatter in a list of cucumber-js formats
|
|
1076
|
+
* (`json:path`, `"json":"path"` or `['json', 'path']`), or '' when there is
|
|
1077
|
+
* none that writes to a file.
|
|
1078
|
+
*
|
|
1079
|
+
* @param {Array<string|string[]>} formats
|
|
1080
|
+
* @returns {string}
|
|
1081
|
+
*/
|
|
1082
|
+
function jsonFormatterFile(formats) {
|
|
1083
|
+
let file = '';
|
|
1084
|
+
for (const format of formats || []) {
|
|
1085
|
+
if (Array.isArray(format)) {
|
|
1086
|
+
if (format[0] === 'json' && format[1]) file = String(format[1]);
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
const match = /^"?json"?:(.+)$/.exec(String(format));
|
|
1090
|
+
if (match) file = match[1].replace(/^"(.*)"$/, '$1');
|
|
1091
|
+
}
|
|
1092
|
+
return file;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
/**
|
|
1096
|
+
* The formats of the cucumber-js config file of this run, for the profiles
|
|
1097
|
+
* the command line names, else the default one. A config file that cannot be
|
|
1098
|
+
* read here (an ES module, a YAML file) gives none.
|
|
1099
|
+
*
|
|
1100
|
+
* @param {string[]} args - The command line of cucumber-js.
|
|
1101
|
+
* @returns {Array<string|string[]>}
|
|
1102
|
+
*/
|
|
1103
|
+
function configFormats(args) {
|
|
1104
|
+
const named = optionValues(args, '--config', '-c');
|
|
1105
|
+
const candidates = named.length
|
|
1106
|
+
? [named[named.length - 1]]
|
|
1107
|
+
: ['cucumber.js', 'cucumber.cjs', 'cucumber.json'];
|
|
1108
|
+
for (const candidate of candidates) {
|
|
1109
|
+
const file = path.resolve(process.cwd(), candidate);
|
|
1110
|
+
if (!/\.(c?js|json)$/.test(file) || !require('fs').existsSync(file)) continue;
|
|
1111
|
+
try {
|
|
1112
|
+
const loaded = require(file);
|
|
1113
|
+
const profiles = optionValues(args, '--profile', '-p');
|
|
1114
|
+
const formats = [];
|
|
1115
|
+
for (const profile of profiles.length ? profiles : ['default']) {
|
|
1116
|
+
const config = (loaded && loaded[profile]) || (profile === 'default' && loaded && !loaded.default ? loaded : null);
|
|
1117
|
+
if (config && Array.isArray(config.format)) formats.push(...config.format);
|
|
1118
|
+
}
|
|
1119
|
+
return formats;
|
|
1120
|
+
} catch {
|
|
1121
|
+
return [];
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
return [];
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
/**
|
|
1128
|
+
* Where this run wrote its JSON report: WEBSHIP_REPORT_JSON, else the file of
|
|
1129
|
+
* the `json` formatter of the command line, else the one of the config file,
|
|
1130
|
+
* else the scaffold's `tests/reports/cucumber_report.json`.
|
|
1131
|
+
*
|
|
1132
|
+
* @returns {string}
|
|
1133
|
+
*/
|
|
1134
|
+
function reportJsonFile() {
|
|
1135
|
+
if (process.env.WEBSHIP_REPORT_JSON) return process.env.WEBSHIP_REPORT_JSON;
|
|
1136
|
+
const args = process.argv.slice(2);
|
|
1137
|
+
return jsonFormatterFile(optionValues(args, '--format', '-f'))
|
|
1138
|
+
|| jsonFormatterFile(configFormats(args))
|
|
1139
|
+
|| 'tests/reports/cucumber_report.json';
|
|
1140
|
+
}
|
|
1141
|
+
|
|
829
1142
|
if (!global.__WEBSHIP_AUTO_REPORT__) {
|
|
830
1143
|
global.__WEBSHIP_AUTO_REPORT__ = true;
|
|
831
1144
|
process.on('exit', () => {
|
|
832
1145
|
if (process.env.WEBSHIP_REPORT_DISABLE) return;
|
|
1146
|
+
// A worker of a --parallel run: the process that runs cucumber-js builds
|
|
1147
|
+
// the report once the whole JSON report is written.
|
|
1148
|
+
if (process.env.CUCUMBER_WORKER_ID) return;
|
|
833
1149
|
try {
|
|
1150
|
+
const json = reportJsonFile();
|
|
1151
|
+
let size = 0;
|
|
1152
|
+
try { size = require('fs').statSync(path.resolve(process.cwd(), json)).size; } catch { /* not written */ }
|
|
1153
|
+
if (!size) {
|
|
1154
|
+
console.error(`[webship-js] No HTML report: this run wrote no JSON report at "${json}". Set WEBSHIP_REPORT_JSON to the file of your json formatter, or WEBSHIP_REPORT_DISABLE=1 to build no report.`);
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
834
1157
|
const { run } = require(path.join(__dirname, '..', '..', 'bin', 'generate-reports'));
|
|
835
1158
|
const extra = (process.env.WEBSHIP_REPORT_ARGS || '').split(/\s+/).filter(Boolean);
|
|
836
|
-
run(extra)
|
|
1159
|
+
Promise.resolve(run(['--json', json].concat(extra))).catch((err) => {
|
|
1160
|
+
console.error('[webship-js] Report generation failed:', err.message);
|
|
1161
|
+
});
|
|
837
1162
|
} catch (err) {
|
|
838
1163
|
console.error('[webship-js] Report generation failed:', err.message);
|
|
839
1164
|
}
|
|
@@ -857,101 +1182,205 @@ const STEP_TIMEOUT = (() => {
|
|
|
857
1182
|
})();
|
|
858
1183
|
setDefaultTimeout(STEP_TIMEOUT);
|
|
859
1184
|
|
|
1185
|
+
// The pacing of worldParameters.minWaitTime, in ms. A project may leave the
|
|
1186
|
+
// block out or set only some of its keys: the others keep these values.
|
|
1187
|
+
const MIN_WAIT_TIME = Object.freeze({
|
|
1188
|
+
page: 3000,
|
|
1189
|
+
before_scenario: 0,
|
|
1190
|
+
after_scenario: 0,
|
|
1191
|
+
before_step: 0,
|
|
1192
|
+
after_step: 0,
|
|
1193
|
+
});
|
|
1194
|
+
|
|
1195
|
+
// BBR: the init script installed on every browser context the World opens.
|
|
1196
|
+
// It runs before any document script and counts in-flight fetch / XHR
|
|
1197
|
+
// requests and pending timers and stamps the last DOM mutation, so
|
|
1198
|
+
// smartSettle() detects the edge of background activity rather than guessing
|
|
1199
|
+
// a fixed delay.
|
|
1200
|
+
function smartWaitProbes() {
|
|
1201
|
+
if (window.__webshipAjaxInstalled) return;
|
|
1202
|
+
window.__webshipAjaxInstalled = true;
|
|
1203
|
+
// The time of the probes is real time: a fake clock (Playwright's
|
|
1204
|
+
// page.clock) replaces Date later, and its Date.now() may stand still or
|
|
1205
|
+
// lie in the past.
|
|
1206
|
+
const realNow = Date.now.bind(Date);
|
|
1207
|
+
window.__webshipNow = realNow;
|
|
1208
|
+
window.__webshipAjaxCount = 0;
|
|
1209
|
+
window.__webshipPendingTimers = 0;
|
|
1210
|
+
window.__webshipLastMutation = realNow();
|
|
1211
|
+
|
|
1212
|
+
// Track in-flight fetch requests.
|
|
1213
|
+
const origFetch = window.fetch;
|
|
1214
|
+
if (typeof origFetch === 'function') {
|
|
1215
|
+
window.fetch = function (...args) {
|
|
1216
|
+
window.__webshipAjaxCount++;
|
|
1217
|
+
const p = origFetch.apply(this, args);
|
|
1218
|
+
const settle = () => { window.__webshipAjaxCount--; };
|
|
1219
|
+
p.then(settle, settle);
|
|
1220
|
+
return p;
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// Track in-flight XMLHttpRequests.
|
|
1225
|
+
const XHR = window.XMLHttpRequest;
|
|
1226
|
+
if (XHR && XHR.prototype) {
|
|
1227
|
+
const origSend = XHR.prototype.send;
|
|
1228
|
+
XHR.prototype.send = function (...args) {
|
|
1229
|
+
window.__webshipAjaxCount++;
|
|
1230
|
+
const settle = () => { window.__webshipAjaxCount--; };
|
|
1231
|
+
this.addEventListener('loadend', settle, { once: true });
|
|
1232
|
+
return origSend.apply(this, args);
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// Track pending setTimeout callbacks. Many client-side frameworks use
|
|
1237
|
+
// setTimeout to schedule UI updates (animation frames, throttled
|
|
1238
|
+
// re-renders, fade-out → display:none). BBR demands we wait for those
|
|
1239
|
+
// timers to drain rather than guess a fixed delay.
|
|
1240
|
+
const origSetTimeout = window.setTimeout;
|
|
1241
|
+
const origClearTimeout = window.clearTimeout;
|
|
1242
|
+
const liveTimers = new Set();
|
|
1243
|
+
if (typeof origSetTimeout === 'function') {
|
|
1244
|
+
window.setTimeout = function (cb, delay, ...args) {
|
|
1245
|
+
window.__webshipPendingTimers++;
|
|
1246
|
+
let id;
|
|
1247
|
+
const wrapped = function () {
|
|
1248
|
+
try {
|
|
1249
|
+
if (typeof cb === 'function') return cb.apply(this, args);
|
|
1250
|
+
} finally {
|
|
1251
|
+
if (liveTimers.delete(id)) window.__webshipPendingTimers--;
|
|
1252
|
+
}
|
|
1253
|
+
};
|
|
1254
|
+
id = origSetTimeout(wrapped, delay);
|
|
1255
|
+
liveTimers.add(id);
|
|
1256
|
+
return id;
|
|
1257
|
+
};
|
|
1258
|
+
if (typeof origClearTimeout === 'function') {
|
|
1259
|
+
window.clearTimeout = function (id) {
|
|
1260
|
+
if (liveTimers.delete(id)) window.__webshipPendingTimers--;
|
|
1261
|
+
return origClearTimeout(id);
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
// Track last DOM mutation so smartSettle can wait for the *edge* of
|
|
1267
|
+
// client-side rendering (animations, async hydration, transitions).
|
|
1268
|
+
const startObserver = () => {
|
|
1269
|
+
if (!document || !document.documentElement) return false;
|
|
1270
|
+
try {
|
|
1271
|
+
new MutationObserver(() => { window.__webshipLastMutation = realNow(); })
|
|
1272
|
+
.observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
|
|
1273
|
+
return true;
|
|
1274
|
+
} catch (e) { return false; }
|
|
1275
|
+
};
|
|
1276
|
+
if (!startObserver()) {
|
|
1277
|
+
document.addEventListener('DOMContentLoaded', startObserver, { once: true });
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
// Functions that set up every page the World opens: the first page of a
|
|
1282
|
+
// scenario and each page a step opens in a new browser context (restoring an
|
|
1283
|
+
// auth state, starting or stopping a video recording). Step files add theirs
|
|
1284
|
+
// with onNewPage().
|
|
1285
|
+
const NEW_PAGE_SETUPS = [];
|
|
1286
|
+
|
|
1287
|
+
/**
|
|
1288
|
+
* Run `setup(world, page)` on every page the World opens from now on, before
|
|
1289
|
+
* any step uses it: the first page of each scenario and every page of a
|
|
1290
|
+
* browser context that a step replaces.
|
|
1291
|
+
*
|
|
1292
|
+
* @param {function(WebshipWorld, import('playwright').Page): (void|Promise<void>)} setup
|
|
1293
|
+
* @returns {void}
|
|
1294
|
+
*/
|
|
1295
|
+
function onNewPage(setup) {
|
|
1296
|
+
if (typeof setup === 'function') NEW_PAGE_SETUPS.push(setup);
|
|
1297
|
+
}
|
|
1298
|
+
|
|
860
1299
|
class PlaywrightWorld extends World {
|
|
861
1300
|
constructor(options) {
|
|
862
1301
|
super(options);
|
|
863
1302
|
this.launchUrl = this.parameters.launchUrl;
|
|
864
|
-
this.minWaitTime = this.parameters.minWaitTime;
|
|
1303
|
+
this.minWaitTime = Object.assign({}, MIN_WAIT_TIME, this.parameters.minWaitTime || {});
|
|
865
1304
|
this.playwrightBrowser = null;
|
|
866
1305
|
this.context = null;
|
|
867
1306
|
this.page = null;
|
|
868
|
-
this.assetsFolder = path.join(
|
|
1307
|
+
this.assetsFolder = path.join(process.cwd(), 'tests', 'assets');
|
|
869
1308
|
}
|
|
870
1309
|
|
|
871
1310
|
async openBrowser(extraContextOptions) {
|
|
872
|
-
const { browser: browserName, launchOptions
|
|
1311
|
+
const { browser: browserName, launchOptions } = playwrightConfig;
|
|
873
1312
|
this.playwrightBrowser = await playwright[browserName].launch(launchOptions);
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
// BBR: install in-flight fetch/XHR counter on every page (init script runs
|
|
877
|
-
// before any document script). The counter lets smartSettle() detect the
|
|
878
|
-
// edge of background activity rather than guessing a fixed delay.
|
|
879
|
-
await this.context.addInitScript(() => {
|
|
880
|
-
if (window.__webshipAjaxInstalled) return;
|
|
881
|
-
window.__webshipAjaxInstalled = true;
|
|
882
|
-
window.__webshipAjaxCount = 0;
|
|
883
|
-
window.__webshipPendingTimers = 0;
|
|
884
|
-
window.__webshipLastMutation = Date.now();
|
|
885
|
-
|
|
886
|
-
// Track in-flight fetch requests.
|
|
887
|
-
const origFetch = window.fetch;
|
|
888
|
-
if (typeof origFetch === 'function') {
|
|
889
|
-
window.fetch = function (...args) {
|
|
890
|
-
window.__webshipAjaxCount++;
|
|
891
|
-
const p = origFetch.apply(this, args);
|
|
892
|
-
const settle = () => { window.__webshipAjaxCount--; };
|
|
893
|
-
p.then(settle, settle);
|
|
894
|
-
return p;
|
|
895
|
-
};
|
|
896
|
-
}
|
|
1313
|
+
await this.openContext(extraContextOptions);
|
|
1314
|
+
}
|
|
897
1315
|
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
1316
|
+
/**
|
|
1317
|
+
* Open a browser context and its page with everything a scenario relies
|
|
1318
|
+
* on: the context options of playwright.config.ts, the scenario's own (the
|
|
1319
|
+
* viewport of an @mobile / @desktop tag, video recording while it is on),
|
|
1320
|
+
* then `extraContextOptions`; the smart-wait init script; and the page
|
|
1321
|
+
* setups registered with onNewPage() (JavaScript-error capture, the
|
|
1322
|
+
* response tracker, the request log, a pending dialog handler).
|
|
1323
|
+
*
|
|
1324
|
+
* @param {import('playwright').BrowserContextOptions} [extraContextOptions]
|
|
1325
|
+
* @returns {Promise<void>}
|
|
1326
|
+
*/
|
|
1327
|
+
async openContext(extraContextOptions) {
|
|
1328
|
+
const options = Object.assign({}, playwrightConfig.contextOptions, this._scenarioContextOptions || {});
|
|
1329
|
+
if (this._videoRequested && this._videoSettings) {
|
|
1330
|
+
fs.mkdirSync(this._videoSettings.dir, { recursive: true });
|
|
1331
|
+
options.recordVideo = { dir: this._videoSettings.dir, size: this._videoSettings.size };
|
|
1332
|
+
}
|
|
1333
|
+
Object.assign(options, extraContextOptions || {});
|
|
1334
|
+
this.context = await this.playwrightBrowser.newContext(options);
|
|
1335
|
+
await this.context.addInitScript(smartWaitProbes);
|
|
1336
|
+
this.page = await this.context.newPage();
|
|
1337
|
+
this.frame = null;
|
|
1338
|
+
for (const setup of NEW_PAGE_SETUPS) await setup(this, this.page);
|
|
1339
|
+
}
|
|
909
1340
|
|
|
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
|
-
return origClearTimeout(id);
|
|
936
|
-
};
|
|
937
|
-
}
|
|
938
|
-
}
|
|
1341
|
+
/**
|
|
1342
|
+
* Replace the browser context in the middle of a scenario (restoring an
|
|
1343
|
+
* auth state, starting a video recording) with one opened by
|
|
1344
|
+
* openContext(), so the new page keeps the smart waits, the viewport of the
|
|
1345
|
+
* scenario, video recording and every page setup. The cookies and the
|
|
1346
|
+
* local storage of the context go over to the new one, unless
|
|
1347
|
+
* `extraContextOptions.storageState` gives others. The new page is blank,
|
|
1348
|
+
* and a video of the context being replaced is not kept.
|
|
1349
|
+
*
|
|
1350
|
+
* @param {import('playwright').BrowserContextOptions} [extraContextOptions]
|
|
1351
|
+
* @returns {Promise<void>}
|
|
1352
|
+
*/
|
|
1353
|
+
async replaceContext(extraContextOptions) {
|
|
1354
|
+
const extra = Object.assign({}, extraContextOptions || {});
|
|
1355
|
+
const outgoing = this.context;
|
|
1356
|
+
const video = this.page && typeof this.page.video === 'function' ? this.page.video() : null;
|
|
1357
|
+
if (outgoing && !('storageState' in extra)) {
|
|
1358
|
+
try { extra.storageState = await outgoing.storageState(); } catch { /* a closed context has nothing to carry */ }
|
|
1359
|
+
}
|
|
1360
|
+
if (outgoing) {
|
|
1361
|
+
try { await outgoing.close(); } catch { /* already closed */ }
|
|
1362
|
+
}
|
|
1363
|
+
if (video) await video.delete().catch(() => {});
|
|
1364
|
+
await this.openContext(extra);
|
|
1365
|
+
}
|
|
939
1366
|
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
1367
|
+
/**
|
|
1368
|
+
* Wait for the page to settle the way the built-in action steps do: no
|
|
1369
|
+
* request in flight, no pending timer and a DOM quiet for 250 ms, bounded
|
|
1370
|
+
* by `budget` ms (by default 1500, the budget after a step). For a
|
|
1371
|
+
* project's own step that changes the page:
|
|
1372
|
+
*
|
|
1373
|
+
* When('I add {string} to the cart', async function (item) {
|
|
1374
|
+
* await this.page.click(`[data-add="${item}"]`);
|
|
1375
|
+
* await this.smartSettle();
|
|
1376
|
+
* });
|
|
1377
|
+
*
|
|
1378
|
+
* @param {number} [budget=1500]
|
|
1379
|
+
* @returns {Promise<void>}
|
|
1380
|
+
*/
|
|
1381
|
+
async smartSettle(budget) {
|
|
1382
|
+
if (!this.page) return;
|
|
1383
|
+
await smartSettle(this.page, typeof budget === 'number' && budget > 0 ? budget : 1500);
|
|
955
1384
|
}
|
|
956
1385
|
|
|
957
1386
|
async closeBrowser() {
|
|
@@ -966,6 +1395,35 @@ class PlaywrightWorld extends World {
|
|
|
966
1395
|
|
|
967
1396
|
setWorldConstructor(PlaywrightWorld);
|
|
968
1397
|
|
|
1398
|
+
// A project extends the World instead of replacing it, so the smart waits,
|
|
1399
|
+
// the viewport tags, video recording and the page setups stay:
|
|
1400
|
+
// const { PlaywrightWorld } = require('webship-js/tests/step-definitions/webship');
|
|
1401
|
+
// setWorldConstructor(class extends PlaywrightWorld { … });
|
|
1402
|
+
module.exports.PlaywrightWorld = PlaywrightWorld;
|
|
1403
|
+
|
|
1404
|
+
let foreignWorldReported = false;
|
|
1405
|
+
|
|
1406
|
+
// A World set with setWorldConstructor that does not extend PlaywrightWorld
|
|
1407
|
+
// has none of what webship-js puts on a page: say so once, plainly.
|
|
1408
|
+
function checkWorld(world) {
|
|
1409
|
+
if (world instanceof PlaywrightWorld) return;
|
|
1410
|
+
// The hooks below read the pacing of the World: give a World of its own
|
|
1411
|
+
// the defaults, so it can still run.
|
|
1412
|
+
if (!world.minWaitTime) world.minWaitTime = Object.assign({}, MIN_WAIT_TIME);
|
|
1413
|
+
if (typeof world.openBrowser !== 'function') {
|
|
1414
|
+
throw friendly(
|
|
1415
|
+
'The World of this run is not a PlaywrightWorld of webship-js, and it has no openBrowser().\n' +
|
|
1416
|
+
" Hint: extend it instead of replacing it: const { PlaywrightWorld } = require('webship-js/tests/step-definitions/webship'); setWorldConstructor(class extends PlaywrightWorld { … });"
|
|
1417
|
+
);
|
|
1418
|
+
}
|
|
1419
|
+
if (foreignWorldReported) return;
|
|
1420
|
+
foreignWorldReported = true;
|
|
1421
|
+
process.stderr.write(
|
|
1422
|
+
'\n[webship-js] The World of this run does not extend PlaywrightWorld: the smart waits, the @mobile / @desktop viewport, video recording and the page setups depend on it. ' +
|
|
1423
|
+
"Extend it instead: const { PlaywrightWorld } = require('webship-js/tests/step-definitions/webship').\n"
|
|
1424
|
+
);
|
|
1425
|
+
}
|
|
1426
|
+
|
|
969
1427
|
// ---------------------------------------------------------------------------
|
|
970
1428
|
// Video recording — Playwright records at browser-context creation. The
|
|
971
1429
|
// helpers below resolve config + tags into either an empty {} (no
|
|
@@ -975,6 +1433,14 @@ setWorldConstructor(PlaywrightWorld);
|
|
|
975
1433
|
|
|
976
1434
|
const VIDEO_MODES = new Set(['off', 'on', 'on-failure', 'tag']);
|
|
977
1435
|
|
|
1436
|
+
// WEBSHIP_VIDEO_SIZE: "<width>x<height>", such as "1280x720".
|
|
1437
|
+
function videoSizeFromEnv() {
|
|
1438
|
+
const m = String(process.env.WEBSHIP_VIDEO_SIZE || '').trim().match(/^(\d+)\s*[x×]\s*(\d+)$/i);
|
|
1439
|
+
return m && parseInt(m[1], 10) > 0 && parseInt(m[2], 10) > 0
|
|
1440
|
+
? { width: parseInt(m[1], 10), height: parseInt(m[2], 10) }
|
|
1441
|
+
: null;
|
|
1442
|
+
}
|
|
1443
|
+
|
|
978
1444
|
function videoSettings(world, scope) {
|
|
979
1445
|
const cfg = (world.parameters && world.parameters.video) || {};
|
|
980
1446
|
let mode = process.env.WEBSHIP_VIDEO || cfg.mode || 'off';
|
|
@@ -982,7 +1448,7 @@ function videoSettings(world, scope) {
|
|
|
982
1448
|
return {
|
|
983
1449
|
mode,
|
|
984
1450
|
dir: process.env.WEBSHIP_VIDEO_DIR || cfg.dir || './videos',
|
|
985
|
-
size: cfg.size || { width: 1280, height: 720 },
|
|
1451
|
+
size: videoSizeFromEnv() || cfg.size || { width: 1280, height: 720 },
|
|
986
1452
|
filenamePattern: cfg.filenamePattern || '{datetime}.{feature_file}.{scenario}.{status}.{ext}',
|
|
987
1453
|
};
|
|
988
1454
|
}
|
|
@@ -1002,68 +1468,185 @@ function sanitisePart(s) {
|
|
|
1002
1468
|
return String(s || '').replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 80);
|
|
1003
1469
|
}
|
|
1004
1470
|
|
|
1005
|
-
|
|
1471
|
+
// The file name of a scenario's video: {datetime} is when the recording
|
|
1472
|
+
// started, {status} the scenario's result in lower case (passed, failed, …),
|
|
1473
|
+
// or the word given for a recording a step stopped. A null status leaves
|
|
1474
|
+
// "<status>" in the name, for a name printed before the scenario ends.
|
|
1475
|
+
function buildVideoFilename(template, scope, status, startedAt) {
|
|
1006
1476
|
const featurePath = (scope && scope.gherkinDocument && scope.gherkinDocument.uri) || 'unknown';
|
|
1007
1477
|
const feature = (scope && scope.gherkinDocument && scope.gherkinDocument.feature && scope.gherkinDocument.feature.name) || 'feature';
|
|
1008
1478
|
const scenario = (scope && scope.pickle && scope.pickle.name) || 'scenario';
|
|
1009
1479
|
const featureFile = featurePath.split('/').pop().replace(/\.feature$/, '');
|
|
1010
|
-
const dt = new Date().toISOString().replace(/[:.]/g, '-');
|
|
1480
|
+
const dt = (startedAt instanceof Date ? startedAt : new Date()).toISOString().replace(/[:.]/g, '-');
|
|
1011
1481
|
return template
|
|
1012
1482
|
.replace('{datetime}', dt)
|
|
1013
1483
|
.replace('{feature_file}', sanitisePart(featureFile))
|
|
1014
1484
|
.replace('{feature}', sanitisePart(feature))
|
|
1015
1485
|
.replace('{scenario}', sanitisePart(scenario))
|
|
1016
|
-
.replace('{status}', sanitisePart(status))
|
|
1486
|
+
.replace('{status}', status === null ? '<status>' : sanitisePart(String(status).toLowerCase()))
|
|
1017
1487
|
.replace('{ext}', 'webm');
|
|
1018
1488
|
}
|
|
1019
1489
|
|
|
1490
|
+
/**
|
|
1491
|
+
* The file name the current video of the scenario is saved under: the name a
|
|
1492
|
+
* step reserved ("I save the current video as"), else the filenamePattern of
|
|
1493
|
+
* worldParameters.video with the given status (null: "<status>").
|
|
1494
|
+
*
|
|
1495
|
+
* @param {WebshipWorld} world
|
|
1496
|
+
* @param {?string} status
|
|
1497
|
+
* @returns {string}
|
|
1498
|
+
*/
|
|
1499
|
+
function videoFileName(world, status) {
|
|
1500
|
+
if (world._videoSaveAsName) return world._videoSaveAsName;
|
|
1501
|
+
const settings = world._videoSettings || videoSettings(world);
|
|
1502
|
+
return buildVideoFilename(settings.filenamePattern, world._scenarioScope, status, world._videoStartedAt);
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1020
1505
|
// ---------------------------------------------------------------------------
|
|
1021
|
-
//
|
|
1022
|
-
// the
|
|
1023
|
-
//
|
|
1024
|
-
//
|
|
1025
|
-
//
|
|
1506
|
+
// Breakpoints: one registry of named viewport sizes for every step and tag
|
|
1507
|
+
// that names a size — the @mobile and @desktop tags, "I set the viewport to
|
|
1508
|
+
// the "…" breakpoint" and "I am viewing the site on a … screen".
|
|
1509
|
+
//
|
|
1510
|
+
// The built-in names come first, then worldParameters.selectors.breakpoints,
|
|
1511
|
+
// then the JSON object of WEBSHIP_SELECTORS_BREAKPOINTS, then the names a
|
|
1512
|
+
// scenario adds with "the following responsive breakpoints:"; each replaces
|
|
1513
|
+
// the sizes of the names it gives and keeps the others. `desktop` stands for
|
|
1514
|
+
// the breakpoint marked `default: true` when the project gives no `desktop`
|
|
1515
|
+
// of its own.
|
|
1026
1516
|
// ---------------------------------------------------------------------------
|
|
1027
1517
|
|
|
1028
|
-
const
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1518
|
+
const BUILT_IN_BREAKPOINTS = Object.freeze({
|
|
1519
|
+
xs: { width: 375, height: 667 },
|
|
1520
|
+
sm: { width: 576, height: 800 },
|
|
1521
|
+
md: { width: 768, height: 1024 },
|
|
1522
|
+
lg: { width: 992, height: 768 },
|
|
1523
|
+
xl: { width: 1200, height: 900 },
|
|
1524
|
+
xxl: { width: 1400, height: 900 },
|
|
1525
|
+
xxxl: { width: 1920, height: 1080 },
|
|
1526
|
+
mobile: { width: 375, height: 667 },
|
|
1527
|
+
tablet: { width: 768, height: 1024 },
|
|
1528
|
+
desktop: { width: 1200, height: 900 },
|
|
1529
|
+
});
|
|
1530
|
+
|
|
1531
|
+
let badBreakpointsReported = false;
|
|
1532
|
+
|
|
1533
|
+
/**
|
|
1534
|
+
* The named sizes of WEBSHIP_SELECTORS_BREAKPOINTS, or an empty object when
|
|
1535
|
+
* it is not set. A value that is not a JSON object of sizes is reported once
|
|
1536
|
+
* and ignored.
|
|
1537
|
+
*
|
|
1538
|
+
* @returns {Object<string, {width: number, height: number}>}
|
|
1539
|
+
*/
|
|
1540
|
+
function breakpointsFromEnv() {
|
|
1541
|
+
const raw = process.env.WEBSHIP_SELECTORS_BREAKPOINTS;
|
|
1542
|
+
if (!raw) return {};
|
|
1543
|
+
try {
|
|
1544
|
+
const parsed = JSON.parse(raw);
|
|
1545
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
|
|
1546
|
+
} catch { /* reported below */ }
|
|
1547
|
+
if (!badBreakpointsReported) {
|
|
1548
|
+
badBreakpointsReported = true;
|
|
1549
|
+
process.stderr.write('\n[webship-js] WEBSHIP_SELECTORS_BREAKPOINTS is not a JSON object of named sizes, such as {"tablet":{"width":800,"height":1280}}; it is ignored.\n');
|
|
1550
|
+
}
|
|
1551
|
+
return {};
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
/**
|
|
1555
|
+
* A `{ width, height }` of whole positive pixels, or null.
|
|
1556
|
+
*
|
|
1557
|
+
* @param {*} size
|
|
1558
|
+
* @returns {{width: number, height: number}|null}
|
|
1559
|
+
*/
|
|
1560
|
+
function breakpointSize(size) {
|
|
1561
|
+
const width = parseInt(size && size.width, 10);
|
|
1562
|
+
const height = parseInt(size && size.height, 10);
|
|
1563
|
+
return width > 0 && height > 0 ? { width, height } : null;
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/**
|
|
1567
|
+
* Every named viewport size the scenario can use, in the order of precedence
|
|
1568
|
+
* described above.
|
|
1569
|
+
*
|
|
1570
|
+
* @param {WebshipWorld} world
|
|
1571
|
+
* @returns {Object<string, {width: number, height: number}>}
|
|
1572
|
+
*/
|
|
1573
|
+
function breakpoints(world) {
|
|
1574
|
+
const configured = (world && world.parameters && world.parameters.selectors && world.parameters.selectors.breakpoints) || {};
|
|
1575
|
+
const fromEnv = breakpointsFromEnv();
|
|
1576
|
+
const named = Object.assign({}, BUILT_IN_BREAKPOINTS);
|
|
1577
|
+
for (const source of [configured, fromEnv]) {
|
|
1578
|
+
for (const [name, value] of Object.entries(source)) {
|
|
1579
|
+
const size = breakpointSize(value);
|
|
1580
|
+
if (size) named[name] = size;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
if (!('desktop' in configured) && !('desktop' in fromEnv)) {
|
|
1584
|
+
const marked = Object.values(Object.assign({}, configured, fromEnv)).find((value) => value && value.default === true);
|
|
1585
|
+
const size = breakpointSize(marked);
|
|
1586
|
+
if (size) named.desktop = size;
|
|
1587
|
+
}
|
|
1588
|
+
return Object.assign(named, (world && world.__scenarioBreakpoints) || {});
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
/**
|
|
1592
|
+
* The size of a named breakpoint. Throws a tester-facing error that lists the
|
|
1593
|
+
* known names when there is no such breakpoint.
|
|
1594
|
+
*
|
|
1595
|
+
* @param {WebshipWorld} world
|
|
1596
|
+
* @param {string} name
|
|
1597
|
+
* @returns {{width: number, height: number}}
|
|
1598
|
+
*/
|
|
1599
|
+
function breakpoint(world, name) {
|
|
1600
|
+
const named = breakpoints(world);
|
|
1601
|
+
const key = String(name === undefined || name === null ? '' : name).trim();
|
|
1602
|
+
if (Object.prototype.hasOwnProperty.call(named, key)) return Object.assign({}, named[key]);
|
|
1603
|
+
throw failure(world && world.page, `There is no breakpoint named "${key}".`, {
|
|
1604
|
+
found: `the breakpoints ${Object.keys(named).join(', ')}`,
|
|
1605
|
+
hint: 'name a size in worldParameters.selectors.breakpoints of cucumber.js, in WEBSHIP_SELECTORS_BREAKPOINTS (a JSON object), or for one scenario with "Given the following responsive breakpoints:".',
|
|
1606
|
+
});
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
// A scenario tagged @mobile or @desktop opens at the size of the `mobile` or
|
|
1610
|
+
// the `desktop` breakpoint. Without either tag the viewport stays fluid
|
|
1611
|
+
// (contextOptions.viewport). A step can still change the viewport inside the
|
|
1612
|
+
// scenario.
|
|
1613
|
+
const TAG_BREAKPOINTS = [['@mobile', 'mobile'], ['@desktop', 'desktop']];
|
|
1032
1614
|
|
|
1033
1615
|
function tagViewport(world, scope) {
|
|
1034
1616
|
const tags = new Set(((scope && scope.pickle && scope.pickle.tags) || []).map((t) => t.name));
|
|
1035
|
-
const entry =
|
|
1036
|
-
|
|
1037
|
-
const [, name, size] = entry;
|
|
1038
|
-
const named = ((world.parameters && world.parameters.selectors && world.parameters.selectors.breakpoints) || {})[name];
|
|
1039
|
-
const width = parseInt(named && named.width, 10);
|
|
1040
|
-
const height = parseInt(named && named.height, 10);
|
|
1041
|
-
return width > 0 && height > 0 ? { width, height } : Object.assign({}, size);
|
|
1617
|
+
const entry = TAG_BREAKPOINTS.find(([tag]) => tags.has(tag));
|
|
1618
|
+
return entry ? breakpoint(world, entry[1]) : null;
|
|
1042
1619
|
}
|
|
1043
1620
|
|
|
1044
|
-
|
|
1621
|
+
// The order of the hooks is the order they are registered in: cucumber-js
|
|
1622
|
+
// runs the Before hooks in that order and the After hooks in the reverse one
|
|
1623
|
+
// (it has no `order` option). This file is loaded before any other hook is
|
|
1624
|
+
// registered — the first step file of the glob and every step file with
|
|
1625
|
+
// hooks of its own require it at their top — so the Before hook below opens
|
|
1626
|
+
// the browser before any other Before hook runs, and the After hook below
|
|
1627
|
+
// closes it after every other After hook ran.
|
|
1628
|
+
Before(async function (scope) {
|
|
1629
|
+
checkWorld(this);
|
|
1630
|
+
this._scenarioScope = scope;
|
|
1045
1631
|
this._videoSettings = videoSettings(this, scope);
|
|
1046
1632
|
this._videoRequested = shouldRecordAtStart(this._videoSettings, scope);
|
|
1047
1633
|
this._videoForcedByTag = videoHasTag(scope, '@video');
|
|
1634
|
+
this._videoStartedAt = this._videoRequested ? new Date() : null;
|
|
1048
1635
|
|
|
1049
|
-
|
|
1636
|
+
// Kept for the whole scenario: a step that replaces the browser context
|
|
1637
|
+
// opens the new one with the same viewport and touch (see openContext).
|
|
1638
|
+
// @touch opens the context with touch on, so "I tap on" fires touch events.
|
|
1050
1639
|
const viewport = tagViewport(this, scope);
|
|
1051
|
-
|
|
1052
|
-
if (this.
|
|
1053
|
-
require('fs').mkdirSync(this._videoSettings.dir, { recursive: true });
|
|
1054
|
-
extra.recordVideo = {
|
|
1055
|
-
dir: this._videoSettings.dir,
|
|
1056
|
-
size: this._videoSettings.size,
|
|
1057
|
-
};
|
|
1058
|
-
}
|
|
1640
|
+
this._scenarioContextOptions = viewport ? { viewport } : {};
|
|
1641
|
+
if (videoHasTag(scope, '@touch')) this._scenarioContextOptions.hasTouch = true;
|
|
1059
1642
|
|
|
1060
|
-
await this.openBrowser(
|
|
1643
|
+
await this.openBrowser();
|
|
1061
1644
|
if (this.minWaitTime.before_scenario > 0) {
|
|
1062
1645
|
await this.page.waitForTimeout(this.minWaitTime.before_scenario);
|
|
1063
1646
|
}
|
|
1064
1647
|
});
|
|
1065
1648
|
|
|
1066
|
-
After(
|
|
1649
|
+
After(async function (scope) {
|
|
1067
1650
|
if (this.minWaitTime.after_scenario > 0) {
|
|
1068
1651
|
try { await this.page.waitForTimeout(this.minWaitTime.after_scenario); } catch { /* page already closed */ }
|
|
1069
1652
|
}
|
|
@@ -1085,11 +1668,13 @@ After({ order: 5 }, async function (scope) {
|
|
|
1085
1668
|
|
|
1086
1669
|
if (videoRef) {
|
|
1087
1670
|
const settings = this._videoSettings;
|
|
1088
|
-
const filename = this
|
|
1671
|
+
const filename = videoFileName(this, status);
|
|
1089
1672
|
const dest = require('path').join(settings.dir, filename);
|
|
1090
1673
|
try {
|
|
1091
1674
|
const passed = status === 'PASSED' || status === 'passed';
|
|
1092
|
-
|
|
1675
|
+
// on-failure keeps a passing scenario's video only when the @video tag
|
|
1676
|
+
// or "I save the current video as" asked for it.
|
|
1677
|
+
if (settings.mode === 'on-failure' && passed && !this._videoForcedByTag && !this._videoSaveAsName) {
|
|
1093
1678
|
await videoRef.delete().catch(() => {});
|
|
1094
1679
|
} else {
|
|
1095
1680
|
await videoRef.saveAs(dest);
|
|
@@ -1120,10 +1705,21 @@ BeforeStep(async function () {
|
|
|
1120
1705
|
}
|
|
1121
1706
|
});
|
|
1122
1707
|
|
|
1123
|
-
// BBR:
|
|
1124
|
-
//
|
|
1125
|
-
//
|
|
1126
|
-
|
|
1708
|
+
// BBR: the verbs of a step that changes the page — the built-in ones (click,
|
|
1709
|
+
// press, fill, …) and the ones a project's own steps use (add, open, delete,
|
|
1710
|
+
// save, log in, …). After such a step, run a short smartSettle so the next
|
|
1711
|
+
// step observes the post-action edge instead of a mid-transition state. The
|
|
1712
|
+
// verbs are read in the step's own words, not in its quoted arguments: "Then
|
|
1713
|
+
// I should see "Delete"" is no action. "scroll" is left out on purpose: a
|
|
1714
|
+
// scroll often starts a loader that the next step checks while it shows. A
|
|
1715
|
+
// project step whose words carry none of them can settle itself with
|
|
1716
|
+
// `await this.smartSettle()`.
|
|
1717
|
+
const STATE_MUTATING_STEP = /\b(click|press|fill|submit|select|check|uncheck|choose|attach|upload|reload|move (?:back|forward)|go to|navigate|on (?:the )?(?:home|front)page|open|close|add|remove|insert|delete|save|publish|edit|update|create|enter|type|clear|reset|drag|drop|hover|tap|toggle|expand|collapse|search|send|request|flush|confirm|cancel|accept|dismiss|log ?in|log ?out|sign ?in|sign ?out)\b/i;
|
|
1718
|
+
|
|
1719
|
+
// The words of a step without its quoted arguments.
|
|
1720
|
+
function stepWords(text) {
|
|
1721
|
+
return String(text).replace(/"(?:[^"\\]|\\.)*"/g, '""');
|
|
1722
|
+
}
|
|
1127
1723
|
|
|
1128
1724
|
AfterStep(async function (scope) {
|
|
1129
1725
|
if (!this.page) return;
|
|
@@ -1134,7 +1730,7 @@ AfterStep(async function (scope) {
|
|
|
1134
1730
|
if (process.env.WEBSHIP_AUTO_SETTLE === 'off') return;
|
|
1135
1731
|
const text = scope && scope.pickleStep && scope.pickleStep.text;
|
|
1136
1732
|
if (typeof text !== 'string') return;
|
|
1137
|
-
if (!STATE_MUTATING_STEP.test(text)) return;
|
|
1733
|
+
if (!STATE_MUTATING_STEP.test(stepWords(text))) return;
|
|
1138
1734
|
try { await smartSettle(this.page, 1500); } catch { /* best effort */ }
|
|
1139
1735
|
});
|
|
1140
1736
|
|