webship-js 2.0.12 → 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.
@@ -98,6 +98,9 @@ jobs:
98
98
  - name: Check that a project step with a page-changing verb is followed by the settle
99
99
  run: npm run test:settle-verbs
100
100
 
101
+ - name: Check that a page load aborted by a network change is loaded once more
102
+ run: npm run test:network-changed
103
+
101
104
  - name: Start virtual server
102
105
  run: npm start &
103
106
 
@@ -318,9 +318,16 @@ function ensurePackageJson(projectPath, opts) {
318
318
  }
319
319
  }
320
320
 
321
- pkg.dependencies = pkg.dependencies || {};
322
- if (opts.force || !pkg.dependencies['webship-js']) {
321
+ // webship-js is listed once: where the project already declares it (a dev or peer dependency
322
+ // included), with its range; --force only refreshes that range. Otherwise it goes under
323
+ // dependencies.
324
+ const declaredIn = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']
325
+ .find((field) => pkg[field] && pkg[field]['webship-js']);
326
+ if (!declaredIn) {
327
+ pkg.dependencies = pkg.dependencies || {};
323
328
  pkg.dependencies['webship-js'] = readPkgVersion();
329
+ } else if (opts.force) {
330
+ pkg[declaredIn]['webship-js'] = readPkgVersion();
324
331
  }
325
332
 
326
333
  fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf8');
@@ -0,0 +1,37 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>Toggle switches and custom checkboxes | Webship-js</title>
6
+ <style>
7
+ /* A toggle switch as cookie consent dialogs draw it: the checkbox is an
8
+ invisible input, and the slider of its label lies on top of it. */
9
+ .switch { position: relative; display: block; height: 30px; margin: 12px 0; }
10
+ .switch input { position: absolute; top: 0; left: 0; opacity: 0; width: 50px; height: 30px; margin: 0; }
11
+ .switch .slider { position: absolute; top: 0; left: 0; width: 50px; height: 30px; background: #ccc; border-radius: 15px; }
12
+ .switch input:checked + label .slider { background: #2a7; }
13
+ .switch .title { margin-left: 60px; line-height: 30px; }
14
+ /* A custom checkbox: the input is not displayed, its label draws the box. */
15
+ .custom input { display: none; }
16
+ .custom label::before { content: ""; display: inline-block; width: 16px; height: 16px; margin-right: 8px; border: 1px solid #333; }
17
+ .custom input:checked + label::before { background: #333; }
18
+ </style>
19
+ </head>
20
+ <body>
21
+ <main>
22
+ <h1>Toggle switches and custom checkboxes</h1>
23
+ <div class="switch">
24
+ <input id="analytics" type="checkbox" aria-labelledby="analytics-title">
25
+ <label for="analytics"><span class="slider"></span><span id="analytics-title" class="title">Analytics cookies</span></label>
26
+ </div>
27
+ <div class="switch">
28
+ <input id="marketing" type="checkbox" aria-labelledby="marketing-title" checked>
29
+ <label for="marketing"><span class="slider"></span><span id="marketing-title" class="title">Marketing cookies</span></label>
30
+ </div>
31
+ <div class="custom">
32
+ <input id="remember" type="checkbox">
33
+ <label for="remember">Remember this device</label>
34
+ </div>
35
+ </main>
36
+ </body>
37
+ </html>
@@ -0,0 +1,37 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>Links and buttons with white space around their text | Webship-js</title>
6
+ </head>
7
+ <body>
8
+ <!-- The way menu templates print their links: the text on a line of its own,
9
+ inside a span, with the indentation of the template around it. -->
10
+ <nav aria-label="Main">
11
+ <ul>
12
+ <li><a href="#products">
13
+ <span class="inner">Products</span>
14
+ </a></li>
15
+ <li><a href="#about-us">About
16
+ us</a></li>
17
+ </ul>
18
+ </nav>
19
+ <main>
20
+ <h1>Links and buttons with white space around their text</h1>
21
+ <button type="button" id="save-draft" onclick="document.getElementById('result').textContent = 'The draft was saved.'">
22
+ Save draft
23
+ </button>
24
+ <table>
25
+ <tbody>
26
+ <tr>
27
+ <td>Order 1042</td>
28
+ <td><a href="#order-1042">
29
+ Edit
30
+ </a></td>
31
+ </tr>
32
+ </tbody>
33
+ </table>
34
+ <p id="result"></p>
35
+ </main>
36
+ </body>
37
+ </html>
@@ -0,0 +1,29 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>A link repeated in a collapsed menu | Webship-js</title>
6
+ <style>.dropdown { display: none; }</style>
7
+ </head>
8
+ <body>
9
+ <!-- The way a store's top menu repeats every category in a dropdown that is
10
+ hidden until the menu opens: the hidden copy comes first in the page. -->
11
+ <nav aria-label="Main">
12
+ <ul>
13
+ <li>Gear
14
+ <ul class="dropdown">
15
+ <li><a role="menuitem" href="#from-the-menu">Bags</a></li>
16
+ <li><a role="menuitem" href="#from-the-menu">Watches</a></li>
17
+ </ul>
18
+ </li>
19
+ </ul>
20
+ </nav>
21
+ <main>
22
+ <h1>A link repeated in a collapsed menu</h1>
23
+ <aside>
24
+ <h2>Shop by category</h2>
25
+ <a href="#bags">Bags</a>
26
+ </aside>
27
+ </main>
28
+ </body>
29
+ </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webship-js",
3
- "version": "2.0.12",
3
+ "version": "2.0.13",
4
4
  "description": "Webship JS automated functional testing.",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -35,6 +35,7 @@
35
35
  "test:world": "node tests/check-world.js",
36
36
  "test:clock": "node tests/check-clock.js",
37
37
  "test:settle-verbs": "node tests/check-settle-verbs.js",
38
+ "test:network-changed": "node tests/check-network-changed.js",
38
39
  "test:fast": "SLOW_MO=0 cucumber-js --config cucumber.js",
39
40
  "test:assets": "node tests/check-assets.js",
40
41
  "test:examples": "node tests/check-examples.js",
@@ -0,0 +1,137 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // Checks that a page load which Chromium aborts with net::ERR_NETWORK_CHANGED
5
+ // (the network of the machine changed under it: a Docker network created or
6
+ // removed, as when another DDEV project starts or stops) is loaded once more,
7
+ // with a line in the log, and that a second abort fails the step as before.
8
+ //
9
+ // A project's Before hook (written here, the way a project writes one) makes
10
+ // the page's goto() throw that error once, or twice, before it loads the
11
+ // page: the real navigation step then runs against a real page.
12
+ //
13
+ // The check serves its own page on a free local port, so no other server is
14
+ // needed.
15
+ //
16
+ // Usage: node tests/check-network-changed.js (npm run test:network-changed)
17
+
18
+ const fs = require('fs');
19
+ const os = require('os');
20
+ const path = require('path');
21
+ const http = require('http');
22
+ const { spawn } = require('child_process');
23
+
24
+ const ROOT = path.resolve(__dirname, '..');
25
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'webship-js-network-changed-'));
26
+ const report = path.join(tmp, 'network.json');
27
+ const config = path.join(tmp, 'cucumber.js');
28
+ const steps = path.join(tmp, 'project.steps.js');
29
+ const feature = path.join(tmp, 'network.feature');
30
+ const cucumber = path.join(ROOT, 'node_modules', '@cucumber', 'cucumber');
31
+
32
+ const PAGE = '<!doctype html><html><head><title>Shop</title></head><body><h1>Shop</h1></body></html>';
33
+
34
+ fs.writeFileSync(steps, [
35
+ `const { Before } = require(${JSON.stringify(cucumber)});`,
36
+ "Before({ tags: '@aborted-once or @aborted-twice' }, function (scope) {",
37
+ " let left = scope.pickle.tags.some((tag) => tag.name === '@aborted-twice') ? 2 : 1;",
38
+ ' const page = this.page;',
39
+ ' const goto = page.goto.bind(page);',
40
+ ' page.goto = async (url, options) => {',
41
+ ' if (left > 0) {',
42
+ ' left -= 1;',
43
+ ' throw new Error(`page.goto: net::ERR_NETWORK_CHANGED at ${url}`);',
44
+ ' }',
45
+ ' return goto(url, options);',
46
+ ' };',
47
+ '});',
48
+ '',
49
+ ].join('\n'));
50
+ fs.writeFileSync(feature, [
51
+ 'Feature: A page load aborted by a change of the network of the machine',
52
+ '',
53
+ ' @aborted-once',
54
+ ' Scenario: The page is loaded once more',
55
+ ' Given I am on "/"',
56
+ ' Then I should see "Shop"',
57
+ '',
58
+ ' @aborted-twice',
59
+ ' Scenario: A second abort fails the step',
60
+ ' Given I am on "/"',
61
+ '',
62
+ ' Scenario: A page load that nothing aborts',
63
+ ' Given I am on "/"',
64
+ ' Then I should see "Shop"',
65
+ '',
66
+ ].join('\n'));
67
+
68
+ const server = http.createServer((req, res) => {
69
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
70
+ res.end(PAGE);
71
+ });
72
+ server.listen(0, '127.0.0.1', () => {
73
+ const base = `http://127.0.0.1:${server.address().port}`;
74
+ const defaults = require(path.join(ROOT, 'cucumber.js')).default;
75
+ const world = JSON.parse(JSON.stringify(defaults.worldParameters));
76
+ world.launchUrl = base;
77
+ fs.writeFileSync(config, 'module.exports = { default: ' + JSON.stringify({
78
+ requireModule: defaults.requireModule,
79
+ require: defaults.require.concat([steps]),
80
+ paths: [feature],
81
+ format: [`json:${report}`],
82
+ worldParameters: world,
83
+ }) + ' };');
84
+ const env = Object.assign({ SLOW_MO: '0' }, process.env, {
85
+ LAUNCH_URL: base,
86
+ WEBSHIP_REPORT_DISABLE: '1',
87
+ WEBSHIP_VIDEO: 'off',
88
+ WEBSHIP_JS_ERROR_MODE: 'off',
89
+ WEBSHIP_SCREENSHOT_ON_FAILED: 'false',
90
+ });
91
+ const run = spawn(process.execPath, [path.join(cucumber, 'bin', 'cucumber.js'), '--config', path.relative(ROOT, config)], {
92
+ cwd: ROOT,
93
+ stdio: ['ignore', 'pipe', 'pipe'],
94
+ env,
95
+ });
96
+ let output = '';
97
+ run.stdout.on('data', (chunk) => { output += chunk; });
98
+ run.stderr.on('data', (chunk) => { output += chunk; });
99
+ const timer = setTimeout(() => run.kill('SIGKILL'), 180000);
100
+ run.on('exit', () => {
101
+ clearTimeout(timer);
102
+ server.close();
103
+ finish(output);
104
+ });
105
+ });
106
+
107
+ function finish(output) {
108
+ const strip = (text) => String(text || '').replace(/\u001b\[[0-9;]*m/g, '');
109
+ const problems = [];
110
+ const results = {};
111
+ if (!fs.existsSync(report) || !fs.readFileSync(report, 'utf8').trim()) {
112
+ problems.push(`The run wrote no report.\n${strip(output).slice(-1500)}`);
113
+ } else {
114
+ for (const f of JSON.parse(fs.readFileSync(report, 'utf8'))) {
115
+ for (const scenario of f.elements || []) {
116
+ const steps = (scenario.steps || []).filter((step) => !step.hidden);
117
+ const failed = steps.find((step) => step.result && step.result.status !== 'passed');
118
+ results[scenario.name] = failed ? { status: failed.result.status, message: strip(failed.result.error_message) } : { status: 'passed' };
119
+ }
120
+ }
121
+ const once = results['The page is loaded once more'];
122
+ const twice = results['A second abort fails the step'];
123
+ const plain = results['A page load that nothing aborts'];
124
+ if (!once || once.status !== 'passed') problems.push(`after one abort the page was not loaded once more: ${once ? once.message.split('\n')[0] : 'the scenario did not run'}`);
125
+ if (!twice || twice.status !== 'failed') problems.push(`after two aborts the step did not fail: ${twice ? twice.status : 'the scenario did not run'}`);
126
+ else if (!/Failed to navigate to/.test(twice.message) || !/ERR_NETWORK_CHANGED/.test(twice.message)) problems.push(`after two aborts the step failed with another message: ${twice.message.split('\n')[0]}`);
127
+ if (!plain || plain.status !== 'passed') problems.push('a page load that nothing aborts did not pass');
128
+ const lines = strip(output).split('\n').filter((line) => /net::ERR_NETWORK_CHANGED, as when a Docker network starts or stops\); loading it once more\./.test(line));
129
+ if (lines.length !== 2) problems.push(`the log says ${lines.length} time(s) that a load was tried once more, not 2 (one per aborted scenario)`);
130
+ }
131
+ fs.rmSync(tmp, { recursive: true, force: true });
132
+ if (problems.length) {
133
+ console.error('A page load aborted by a network change:\n - ' + problems.join('\n - '));
134
+ process.exit(1);
135
+ }
136
+ console.log('A page load aborted by a network change is loaded once more and the log says so; a second abort fails the step.');
137
+ }
@@ -10,8 +10,9 @@
10
10
  // 2. `npm test` in that project is green against a site (the examples/
11
11
  // pages of this repository, served on a free port),
12
12
  // 3. a feature named on the command line runs alone,
13
- // 4. a second scaffold run changes nothing, and a `test` script the project
14
- // chose itself is kept,
13
+ // 4. a second scaffold run changes nothing, a `test` script the project
14
+ // chose itself is kept, and webship-js declared as a dev or peer
15
+ // dependency is not listed a second time,
15
16
  // 5. a `test` script that runs Nightwatch (a project from webship-js 1.x)
16
17
  // is replaced by the suite and kept as `test:nightwatch`,
17
18
  // 6. `--force` rewrites the scaffold's files but keeps the project's own
@@ -188,6 +189,22 @@ async function main() {
188
189
  if (ownPkg.scripts.test !== 'node my-own-tests.js') problems.push(`the scaffold replaced a test script of the project: ${ownPkg.scripts.test}`);
189
190
  if (!ownPkg.scripts['test:chromium']) problems.push('the scaffold did not add test:chromium beside an existing test script');
190
191
 
192
+ // webship-js already declared as a dev dependency (or a peer): the scaffold leaves it there, with
193
+ // its range, and does not list it a second time under dependencies.
194
+ for (const field of ['devDependencies', 'peerDependencies']) {
195
+ const declared = path.join(tmp, `declared-in-${field}`);
196
+ fs.mkdirSync(declared);
197
+ fs.writeFileSync(path.join(declared, 'package.json'), JSON.stringify({ name: `declared-in-${field.toLowerCase()}`, version: '1.0.0', [field]: { 'webship-js': '^2.0.12' } }, null, 2));
198
+ scaffold(declared);
199
+ const declaredPkg = JSON.parse(fs.readFileSync(path.join(declared, 'package.json'), 'utf8'));
200
+ if (declaredPkg.dependencies && declaredPkg.dependencies['webship-js']) {
201
+ problems.push(`with webship-js in ${field}, the scaffold listed it again under dependencies (${declaredPkg.dependencies['webship-js']})`);
202
+ }
203
+ if ((declaredPkg[field] || {})['webship-js'] !== '^2.0.12') {
204
+ problems.push(`the scaffold changed the range of webship-js in ${field}: ${(declaredPkg[field] || {})['webship-js']}`);
205
+ }
206
+ }
207
+
191
208
  // A project from webship-js 1.x: its test script runs Nightwatch.
192
209
  const legacy = path.join(tmp, 'from-1x');
193
210
  fs.mkdirSync(legacy);
@@ -0,0 +1,28 @@
1
+ Feature: Toggle switches and custom checkboxes
2
+ As a tester
3
+ I want to check and uncheck a box the way a person does
4
+ So that a slider drawn over the checkbox, or a box drawn by its label, does not stop the step
5
+
6
+ Scenario: Check a switch whose slider covers its checkbox
7
+ Given I am on "/check-switch.html"
8
+ When I check "Analytics cookies"
9
+ Then the checkbox "Analytics cookies" should be checked
10
+
11
+ Scenario: Uncheck a switch that is on
12
+ Given I am on "/check-switch.html"
13
+ When I uncheck "Marketing cookies"
14
+ Then the checkbox "Marketing cookies" should not be checked
15
+
16
+ Scenario: Check and uncheck a switch named by its checkbox
17
+ Given I am on "/check-switch.html"
18
+ When I check the checkbox "#analytics"
19
+ Then the checkbox "#analytics" should be checked
20
+ When I uncheck the checkbox "#analytics"
21
+ Then the checkbox "#analytics" should not be checked
22
+
23
+ Scenario: Check a checkbox whose input is hidden and whose label draws the box
24
+ Given I am on "/check-switch.html"
25
+ When I check "Remember this device"
26
+ Then the checkbox "Remember this device" should be checked
27
+ When I uncheck "Remember this device"
28
+ Then the checkbox "Remember this device" should not be checked
@@ -0,0 +1,29 @@
1
+ Feature: Links and buttons whose markup puts white space around their text
2
+ As a tester
3
+ I want to click a link and press a button by the text a person reads
4
+ So that the indentation of a template does not hide them from the steps
5
+
6
+ Scenario: Click a link whose text sits on a line of its own
7
+ Given I am on "/click-whitespace.html"
8
+ When I click "Products"
9
+ Then the url should match "#products$"
10
+
11
+ Scenario: Click a link whose text breaks across lines
12
+ Given I am on "/click-whitespace.html"
13
+ When I click "About us"
14
+ Then the url should match "#about-us$"
15
+
16
+ Scenario: Press a button whose label is indented
17
+ Given I am on "/click-whitespace.html"
18
+ When I press "Save draft"
19
+ Then I should see "The draft was saved."
20
+
21
+ Scenario: Click a link of a table row whose text is indented
22
+ Given I am on "/click-whitespace.html"
23
+ When I click "Edit" in the "Order 1042" row
24
+ Then the url should match "#order-1042$"
25
+
26
+ Scenario: Follow a link whose text sits on a line of its own
27
+ Given I am on "/click-whitespace.html"
28
+ When I follow "Products"
29
+ Then the url should match "#products$"
@@ -0,0 +1,9 @@
1
+ Feature: Follow the link a person sees when a collapsed menu repeats it first
2
+ As a tester
3
+ I want to follow a link by its text
4
+ So that a hidden copy of it in a closed menu is not the one the step waits on
5
+
6
+ Scenario: Follow a link whose hidden copy comes first in the page
7
+ Given I am on "/follow-hidden-first.html"
8
+ When I follow "Bags"
9
+ Then the url should match "#bags$"
@@ -35,6 +35,16 @@ function clickRegistryHint(world, name) {
35
35
  });
36
36
  }
37
37
 
38
+ // The whole text of a link or a button as a person reads it. A template that
39
+ // prints the text on its own line (`<a>\n <span>Products</span>\n</a>`, the
40
+ // way Drupal's menus do) gives the element white space around its text, and
41
+ // a long label can break across lines: both still match, the text itself is
42
+ // matched whole and literally.
43
+ function wholeText(text) {
44
+ const words = String(text).trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
45
+ return new RegExp('^\\s*' + words + '\\s*$');
46
+ }
47
+
38
48
  // ---------------------------------------------------------------------------
39
49
  // Press / click — by visible text
40
50
  // ---------------------------------------------------------------------------
@@ -50,11 +60,10 @@ function clickRegistryHint(world, name) {
50
60
  *
51
61
  */
52
62
  When(/^(I |we )*press( the)* "([^"]*)?"( button)*$/, async function (pronounCase, theCase, element, buttonCase) {
53
- const esc = element.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
54
63
  const page = this.page;
55
64
  await actOrExplain('press button', element, async () => {
56
65
  await page.locator('button, input[type="button"], input[type="submit"], [role="button"], a')
57
- .filter({ hasText: new RegExp('^' + esc + '$') })
66
+ .filter({ hasText: wholeText(element) })
58
67
  .first()
59
68
  .click();
60
69
  }, clickRegistryHint(this, element));
@@ -85,11 +94,10 @@ When(/^(I |we )*press "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, a
85
94
  *
86
95
  */
87
96
  When(/^(I |we )*click "([^"]*)?"$/, async function (pronounCase, item) {
88
- const esc = item.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
89
97
  const page = this.page;
90
98
  await actOrExplain('click', item, async () => {
91
99
  await page.locator('a, button, [role="button"], input[type="button"], input[type="submit"]')
92
- .filter({ hasText: new RegExp('^' + esc + '$') })
100
+ .filter({ hasText: wholeText(item) })
93
101
  .first()
94
102
  .click();
95
103
  }, clickRegistryHint(this, item));
@@ -120,10 +128,9 @@ When(/^(I |we )*click "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, a
120
128
  *
121
129
  */
122
130
  When(/^(I |we )*click "([^"]*)?" in( the)* "([^"]*)?" row$/, async function (pronounCase, clickText, theCase, rowIdentifier) {
123
- const esc = clickText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
124
131
  const row = this.page.locator('tr').filter({ hasText: rowIdentifier }).first();
125
132
  const clickable = row.locator('a, button, [role="button"], input[type="submit"], input[type="button"]')
126
- .filter({ hasText: new RegExp('^' + esc + '$') });
133
+ .filter({ hasText: wholeText(clickText) });
127
134
  if (await clickable.count() > 0) {
128
135
  await clickable.first().click();
129
136
  } else {
@@ -134,7 +141,8 @@ When(/^(I |we )*click "([^"]*)?" in( the)* "([^"]*)?" row$/, async function (pro
134
141
  /**
135
142
  * Follow a link by its visible text.
136
143
  * Uses Playwright's accessibility-first `getByRole('link', { name })` with a
137
- * text-match fallback.
144
+ * text-match fallback, and follows the first link of that name a person can
145
+ * see: a hidden copy in a collapsed menu is passed over.
138
146
  *
139
147
  * Example #1: When I follow "Contact Us"
140
148
  * Example #2: When I follow "About"
@@ -148,13 +156,24 @@ When(/^(I |we )*click "([^"]*)?" in( the)* "([^"]*)?" row$/, async function (pro
148
156
  * Example #10: When I follow "Next"
149
157
  */
150
158
  When(/^(I |we )*follow "([^"]*)"$/, async function (pronounCase, link) {
151
- const esc = link.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
152
159
  const page = this.page;
153
160
  await actOrExplain('follow link', link, async () => {
154
- const loc = page.getByRole('link', { name: link, exact: true }).or(
155
- page.locator('a').filter({ hasText: new RegExp('^' + esc + '$') })
156
- ).first();
157
- await loc.click();
161
+ const matches = page.getByRole('link', { name: link, exact: true }).or(
162
+ page.locator('a').filter({ hasText: wholeText(link) })
163
+ );
164
+ // A site that repeats its links in a collapsed menu (a dropdown, a mobile
165
+ // menu kept in the page) puts a hidden copy first: the link a person sees
166
+ // and follows is the first visible one.
167
+ const visible = matches.filter({ visible: true }).first();
168
+ if (await visible.waitFor({ state: 'visible', timeout: 5000 }).then(() => true, () => false)) {
169
+ await visible.click();
170
+ return;
171
+ }
172
+ const found = await matches.count();
173
+ if (found > 0) {
174
+ throw new Error(`the page has ${found === 1 ? 'a link' : `${found} links`} named "${link}", but none is visible (a closed menu, a hidden section).`);
175
+ }
176
+ await matches.first().click();
158
177
  });
159
178
  });
160
179
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  const { Given, When, Then } = require('@cucumber/cucumber');
6
6
  const assert = require('assert');
7
- const { friendly, failure, fillLocator, humanize, isTimeout } = require('./webship');
7
+ const { friendly, failure, fillLocator, humanize, isTimeout, setChecked } = require('./webship');
8
8
 
9
9
  // Resolve a field by label, name, id, or selector.
10
10
  function fieldLocator(page, field) {
@@ -220,7 +220,7 @@ async function setChoice(world, name, kind, action) {
220
220
  const spec = CONTROLS[kind];
221
221
  const loc = await locateControl(world.page, name, kind);
222
222
  try {
223
- await loc[action]({ timeout: 5000 });
223
+ await setChecked(loc, action === 'check', { timeout: 5000 });
224
224
  } catch (e) {
225
225
  throw failure(world.page, `Could not ${action === 'check' && kind === 'radio' ? 'select' : action} the ${spec.noun} "${name}".`, {
226
226
  hint: `${humanize(e)}; a ${spec.noun} that is hidden or disabled cannot be changed.`,
@@ -714,7 +714,8 @@ When(/^(I |we )*clear the select "([^"]*)"$/, async function (pronoun, sel) {
714
714
  });
715
715
 
716
716
  /**
717
- * Check a checkbox.
717
+ * Check a checkbox. One whose input is covered by a part of its own label (a toggle
718
+ * switch) or hidden (a box drawn by its label) is clicked through its label.
718
719
  *
719
720
  * The checkbox is named by a CSS selector, the exact text of its label, its
720
721
  * name, its id or its value; one that is not found within 5 seconds fails
@@ -732,7 +733,8 @@ When(/^(I |we )*check the checkbox "([^"]*)"$/, async function (pronoun, sel) {
732
733
  });
733
734
 
734
735
  /**
735
- * Uncheck a checkbox.
736
+ * Uncheck a checkbox. One whose input is covered by a part of its own label (a toggle
737
+ * switch) or hidden (a box drawn by its label) is clicked through its label.
736
738
  *
737
739
  * The checkbox is named by a CSS selector, the exact text of its label, its
738
740
  * name, its id or its value; one that is not found within 5 seconds fails
@@ -750,7 +752,8 @@ When(/^(I |we )*uncheck the checkbox "([^"]*)"$/, async function (pronoun, sel)
750
752
  });
751
753
 
752
754
  /**
753
- * Select a radio button.
755
+ * Select a radio button. One whose input is covered by a part of its own label (a toggle
756
+ * switch) or hidden (a box drawn by its label) is clicked through its label.
754
757
  *
755
758
  * The radio button is named by a CSS selector, the exact text of its label,
756
759
  * its id or its value (not its name, which its whole group shares); one that
@@ -5,7 +5,7 @@
5
5
  // check / uncheck, radio buttons.
6
6
 
7
7
  const { When } = require('@cucumber/cucumber');
8
- const { buildSelector, fillField, fillLocator, friendly, failure, humanize, isTimeout } = require('./webship');
8
+ const { buildSelector, fillField, fillLocator, friendly, failure, humanize, isTimeout, setChecked } = require('./webship');
9
9
 
10
10
  // ---------------------------------------------------------------------------
11
11
  // Fill — by label, attribute, table, reverse syntax
@@ -287,7 +287,9 @@ When(/^(I |we )*additionally select "([^"]*)" from "([^"]*)"$/, async function (
287
287
  // ---------------------------------------------------------------------------
288
288
 
289
289
  /**
290
- * Checks the specified checkbox by label, id, class, or name.
290
+ * Checks the specified checkbox by label, id, class, or name. A toggle
291
+ * switch whose slider covers its checkbox, and a checkbox whose label draws
292
+ * the box, are clicked through their label, as a person does.
291
293
  *
292
294
  * Example #1: When I check "Remember me"
293
295
  * Example #2: When we check "Put site into maintenance mode"
@@ -299,13 +301,13 @@ When(/^(I |we )*additionally select "([^"]*)" from "([^"]*)"$/, async function (
299
301
  When(/^(I |we )*check "([^"]*)?"$/, async function (pronounCase, item) {
300
302
  try {
301
303
  if (item.startsWith('#') || item.startsWith('.')) {
302
- await this.page.locator(item).check();
304
+ await setChecked(this.page.locator(item), true);
303
305
  } else {
304
306
  const byLabel = this.page.getByLabel(item, { exact: true });
305
307
  if (await byLabel.count() > 0) {
306
- await byLabel.check();
308
+ await setChecked(byLabel, true);
307
309
  } else {
308
- await this.page.locator(`input[type="checkbox"][id="${item}"], input[type="checkbox"][name="${item}"], input[type="checkbox"][value="${item}"]`).first().check();
310
+ await setChecked(this.page.locator(`input[type="checkbox"][id="${item}"], input[type="checkbox"][name="${item}"], input[type="checkbox"][value="${item}"]`).first(), true);
309
311
  }
310
312
  }
311
313
  } catch (e) {
@@ -318,7 +320,9 @@ When(/^(I |we )*check "([^"]*)?"$/, async function (pronounCase, item) {
318
320
  });
319
321
 
320
322
  /**
321
- * Unchecks the specified checkbox by label, id, class, or name.
323
+ * Unchecks the specified checkbox by label, id, class, or name. A toggle
324
+ * switch whose slider covers its checkbox, and a checkbox whose label draws
325
+ * the box, are clicked through their label, as a person does.
322
326
  *
323
327
  * Example #1: When I uncheck "Remember me"
324
328
  * Example #2: When we uncheck "Put site into maintenance mode"
@@ -330,13 +334,13 @@ When(/^(I |we )*check "([^"]*)?"$/, async function (pronounCase, item) {
330
334
  When(/^(I |we )*uncheck "([^"]*)?"$/, async function (pronounCase, item) {
331
335
  try {
332
336
  if (item.startsWith('#') || item.startsWith('.')) {
333
- await this.page.locator(item).uncheck();
337
+ await setChecked(this.page.locator(item), false);
334
338
  } else {
335
339
  const byLabel = this.page.getByLabel(item, { exact: true });
336
340
  if (await byLabel.count() > 0) {
337
- await byLabel.uncheck();
341
+ await setChecked(byLabel, false);
338
342
  } else {
339
- await this.page.locator(`input[type="checkbox"][id="${item}"], input[type="checkbox"][name="${item}"], input[type="checkbox"][value="${item}"]`).first().uncheck();
343
+ await setChecked(this.page.locator(`input[type="checkbox"][id="${item}"], input[type="checkbox"][name="${item}"], input[type="checkbox"][value="${item}"]`).first(), false);
340
344
  }
341
345
  }
342
346
  } catch (e) {
@@ -439,7 +439,9 @@ async function sendRequest(world, { method, url, headers, data, session }) {
439
439
 
440
440
  /**
441
441
  * Navigate to a URL with friendly error messages for common failures
442
- * (server down, DNS, empty response). All other errors rethrow with
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
443
445
  * preserved stack + extra context.
444
446
  *
445
447
  * @param {import('playwright').Page} page
@@ -448,7 +450,18 @@ async function sendRequest(world, { method, url, headers, data, session }) {
448
450
  */
449
451
  async function gotoUrl(page, url) {
450
452
  try {
451
- await page.goto(url, { waitUntil: 'domcontentloaded' });
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
+ }
452
465
  } catch (e) {
453
466
  const msg = e.message || '';
454
467
  // Empty response: harmless, swallow.
@@ -926,6 +939,50 @@ function isTimeout(error) {
926
939
  return !!error && (error.name === 'TimeoutError' || /Timeout \d+ms exceeded/.test(String(error.message || '')));
927
940
  }
928
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
+
929
986
  /**
930
987
  * Build the failure of an assertion for a tester: what was looked for, what
931
988
  * was found, the address of the page and a hint. No call log, no stack.
@@ -975,6 +1032,7 @@ module.exports = {
975
1032
  failure,
976
1033
  excerpt,
977
1034
  isTimeout,
1035
+ setChecked,
978
1036
  registeredNameHint,
979
1037
  pageTextLocator,
980
1038
  breakpoints,