@webship-js/vue-steps 0.0.0-stage → 2.0.0

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.
@@ -0,0 +1,294 @@
1
+ 'use strict';
2
+
3
+ // Shared helpers for the step files of this pack.
4
+ //
5
+ // Not a step file: it registers no step definitions and no hooks. It puts the page side of the pack
6
+ // (vue-probe.js) into every page the World opens, records the status of each page the browser loads, and
7
+ // holds the plumbing the steps use and that a project can require for its own steps: the wait budgets,
8
+ // the poll on the page, waiting for the app to wire the page up, waiting for the page to be still,
9
+ // following a navigation to its end, finding a link or a button by the name a person reads, and the
10
+ // failure messages.
11
+ //
12
+ // The waits are the point of the pack. A Nuxt page arrives as the server's HTML; the app then wires it up
13
+ // in the browser (until then its links load whole pages and its buttons do nothing yet). After that, the
14
+ // app moves between views inside the page, fetches each view's data, sends a form in place, and moves
15
+ // things with frames and transitions. The steps wait for each of those to end, on the page's own
16
+ // signals: the app's own state (Nuxt's isHydrating, or a mounted Vue app), its router's navigations
17
+ // (Nuxt's page:loading hooks, or Vue Router's guards), the id of the document (so a navigation inside
18
+ // the app is told from a whole load without counting on a request), the requests in flight, the frames
19
+ // asked for and the animations running. No step sleeps for a fixed time.
20
+ //
21
+ // Everything builds on webship-js's own helpers (`onNewPage`, `friendly`, `failure`) so the steps fail
22
+ // the way the core webship-js steps do.
23
+
24
+ const webship = require('webship-js/tests/step-definitions/webship');
25
+ const { appProbe } = require('./vue-probe');
26
+
27
+ const { friendly, failure, onNewPage } = webship;
28
+
29
+ /** The page side as a script: it installs `window.__webshipVue`. */
30
+ const PROBE = `(${appProbe.toString()})();`;
31
+
32
+ // Every page the World opens gets the probe before its own scripts run, and every document it loads
33
+ // leaves its status and address for the steps that read an error page or a form sent with a page load.
34
+ if (typeof onNewPage === 'function') {
35
+ onNewPage(async (world, page) => {
36
+ try { await page.addInitScript(PROBE); } catch (e) { /* a closed page needs nothing */ }
37
+ page.on('request', (request) => {
38
+ try {
39
+ if (request.isNavigationRequest() && request.frame() === page.mainFrame()) world.vueLoadStarted = Date.now();
40
+ } catch (e) { /* a page that closed meanwhile */ }
41
+ });
42
+ page.on('response', (response) => {
43
+ try {
44
+ const request = response.request();
45
+ if (request.isNavigationRequest() && response.frame() === page.mainFrame()) {
46
+ world.vueDocuments = (world.vueDocuments || []).concat([{ url: response.url(), status: response.status(), method: request.method(), at: Date.now() }]).slice(-10);
47
+ world.vueDocument = world.vueDocuments[world.vueDocuments.length - 1];
48
+ }
49
+ } catch (e) { /* a page that closed meanwhile */ }
50
+ });
51
+ });
52
+ }
53
+
54
+ /**
55
+ * The per-assertion wait budget: `minWaitTime.page` from cucumber.js, at least 10 seconds. Kept below
56
+ * webship-js's 45 second step timeout. COMPONENT_WAIT_MS sets it outright (the run of the assertions
57
+ * that must fail uses a short one: each of them waits its whole budget).
58
+ */
59
+ function budget(world) {
60
+ const fixed = Number(process.env.COMPONENT_WAIT_MS);
61
+ if (Number.isFinite(fixed) && fixed > 0) return Math.min(fixed, 40000);
62
+ const page = world && world.minWaitTime && world.minWaitTime.page;
63
+ return Math.min(Math.max(page || 0, 10000), 40000);
64
+ }
65
+
66
+ /** White space collapsed, typographic quotes made plain: the way the steps compare texts. */
67
+ function norm(text) {
68
+ return String(text === null || text === undefined ? '' : text)
69
+ .replace(/[‘’‚‛′]/g, "'")
70
+ .replace(/[“”„″]/g, '"')
71
+ .replace(/[ ]/g, ' ')
72
+ .replace(/\s+/g, ' ')
73
+ .trim();
74
+ }
75
+
76
+ /** A list for a failure message: `"a", "b"` or `(none)`. */
77
+ function listed(values, max) {
78
+ const items = [...new Set((values || []).map(norm).filter(Boolean))];
79
+ const limit = max || 12;
80
+ if (!items.length) return '(none)';
81
+ const shown = items.slice(0, limit).map((v) => `"${v}"`).join(', ');
82
+ return items.length > limit ? `${shown} and ${items.length - limit} more` : shown;
83
+ }
84
+
85
+ /** Shorten a text for a message. */
86
+ function excerpt(text, max) {
87
+ const clean = norm(text);
88
+ const limit = max || 160;
89
+ return clean.length > limit ? `${clean.slice(0, limit)}…` : clean;
90
+ }
91
+
92
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
93
+
94
+ /** Put the probe into the current page when it is not there (a page opened before this pack was loaded,
95
+ * or a browser without JavaScript, where an init script does not run). */
96
+ async function ensureProbe(world) {
97
+ let there = false;
98
+ try {
99
+ there = await world.page.evaluate(() => !!(window.__webshipVue && window.__webshipVue.lib));
100
+ } catch (e) {
101
+ there = false;
102
+ }
103
+ if (!there) {
104
+ try { await world.page.evaluate(PROBE); } catch (e) { /* the page is navigating: the next call retries */ }
105
+ }
106
+ }
107
+
108
+ /** Run a function of the page side's library: `call(world, 'firstHeading')`. */
109
+ async function call(world, name, ...args) {
110
+ await ensureProbe(world);
111
+ return world.page.evaluate(([fn, list]) => window.__webshipVue.lib[fn](...list), [name, args]);
112
+ }
113
+
114
+ /** The page side's state, or null while the page is between two documents. */
115
+ async function pageState(world) {
116
+ try {
117
+ await ensureProbe(world);
118
+ return await world.page.evaluate(() => (window.__webshipVue ? window.__webshipVue.lib.state() : null));
119
+ } catch (e) {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Look at the page every 50 ms, from Node (a timer in the page would be counted by webship-js as pending
126
+ * work), until `check` returns a value with `done: true` or the time is up. `check` gets the page side's
127
+ * state (null between two documents). Returns the last value it gave.
128
+ */
129
+ async function poll(world, check, timeout) {
130
+ const deadline = Date.now() + timeout;
131
+ let last = { done: false };
132
+ for (;;) {
133
+ const state = await pageState(world);
134
+ let value = null;
135
+ try { value = await check(state); } catch (e) { value = { done: false, error: e.message }; }
136
+ if (value) last = value;
137
+ if (value && value.done) return value;
138
+ if (Date.now() + 50 >= deadline) return last;
139
+ await sleep(50);
140
+ }
141
+ }
142
+
143
+ /** Is the browser of this scenario without JavaScript? The lane of the suite, named in its failures. */
144
+ async function lane(world) {
145
+ try {
146
+ const js = await call(world, 'jsOn');
147
+ return js ? 'JavaScript on' : 'JavaScript off';
148
+ } catch (e) {
149
+ return 'unknown';
150
+ }
151
+ }
152
+
153
+ /** A failure that names the lane when the browser runs without JavaScript, so a failure of that lane is
154
+ * never read as one of the other. */
155
+ async function laneFailure(world, message, details) {
156
+ const which = await lane(world);
157
+ const more = { ...(details || {}) };
158
+ if (which === 'JavaScript off') more.found = `${more.found ? `${more.found}; ` : ''}this run's browser has JavaScript off`;
159
+ return failure(world.page, message, more);
160
+ }
161
+
162
+ /**
163
+ * Wait until the app has wired the page up, when it can: a page with a Vue app, in a browser with
164
+ * JavaScript. Returns what it found: `wired`, `app` (the page has an app to wire it up), `js`.
165
+ */
166
+ async function wiredUp(world, timeout) {
167
+ const result = await poll(world, (s) => ({ done: !!s && (!s.app || !s.js || s.wired) && s.readyState !== 'loading', state: s }), timeout || budget(world));
168
+ const s = result.state || {};
169
+ return { wired: !!(s.app && s.js && s.wired), app: !!s.app, js: s.js !== false, done: result.done, state: s };
170
+ }
171
+
172
+ /** A line in the run's log: the scenario's own (cucumber's `log`), else the console. */
173
+ function note(world, text) {
174
+ try {
175
+ if (world && typeof world.log === 'function') { world.log(text); return; }
176
+ } catch (e) { /* no log in this World */ }
177
+ console.log(`[vue-steps] ${text}`);
178
+ }
179
+
180
+ /** Wait for the app to wire the page up before a step acts on it; a page without an app or a browser
181
+ * without JavaScript is not waited on, and the log says so once per document. */
182
+ async function beforeActing(world) {
183
+ const w = await wiredUp(world);
184
+ const s = w.state || {};
185
+ if (!w.app || !w.js) {
186
+ world.vueNoted = world.vueNoted || new Set();
187
+ if (s.doc && !world.vueNoted.has(s.doc)) {
188
+ world.vueNoted.add(s.doc);
189
+ note(world, !w.js ? 'This browser has JavaScript off: the steps do not wait for the app to wire the page up.' : `${s.url || 'The page'} has no app to wire it up, and the steps do not wait for one.`);
190
+ }
191
+ }
192
+ return w;
193
+ }
194
+
195
+ /** Wait until the page is still (see vue-probe.js). Returns the last state; never fails. */
196
+ async function still(world, timeout) {
197
+ return poll(world, (s) => ({ done: !!s && s.still, state: s }), timeout || Math.min(budget(world), 5000));
198
+ }
199
+
200
+ /** Escape a text for a regular expression. */
201
+ function escapeRe(text) {
202
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
203
+ }
204
+
205
+ /**
206
+ * The element of a role and a name, the way a person names it (Playwright's accessible name): an exact
207
+ * name, then without regard to case, then a name that starts with the text (three characters or more);
208
+ * never a part in the middle. The first one on the screen wins. `scope` narrows the search (a locator).
209
+ * Returns `{ locator, names }`; `locator` is null when there is none.
210
+ */
211
+ async function byRoleAndName(world, role, name, scope) {
212
+ const root = scope || world.page;
213
+ const clean = norm(name);
214
+ const tries = [
215
+ { name: clean, exact: true },
216
+ { name: new RegExp(`^\\s*${escapeRe(clean)}\\s*$`, 'i') },
217
+ ];
218
+ if (clean.length >= 3) tries.push({ name: new RegExp(`^\\s*${escapeRe(clean)}`, 'i') });
219
+ for (const options of tries) {
220
+ const all = root.getByRole(role, options);
221
+ const count = await all.count();
222
+ for (let i = 0; i < count; i += 1) {
223
+ const one = all.nth(i);
224
+ if (await one.isVisible().catch(() => false)) return { locator: one, names: [] };
225
+ }
226
+ if (count) return { locator: all.first(), names: [] };
227
+ }
228
+ return { locator: null, names: await namesOf(root, role) };
229
+ }
230
+
231
+ /** The accessible names of the elements of a role (30 at most), the way the steps match them. */
232
+ async function namesOf(root, role) {
233
+ const all = root.getByRole(role);
234
+ const count = Math.min(await all.count().catch(() => 0), 30);
235
+ const names = [];
236
+ for (let i = 0; i < count; i += 1) {
237
+ const snap = await all.nth(i).ariaSnapshot({ timeout: 1000 }).catch(() => '');
238
+ const m = String(snap).split('\n')[0].match(/^- [a-z]+ "((?:[^"\\]|\\.)*)"/);
239
+ if (m) names.push(m[1].replace(/\\"/g, '"'));
240
+ }
241
+ return names;
242
+ }
243
+
244
+ /**
245
+ * Follow what a step started to its end:
246
+ * - a change of view inside the app: the same document, a navigation of the app's router started and
247
+ * ended (Nuxt's page:loading hooks, Vue Router's guards) or a new route, the route announcer (when the
248
+ * app has one) holding the new title, and the page still;
249
+ * - a whole page load: a new document, loaded, wired up when it can be, and still.
250
+ * `sameAddress`: the step went to the address the page is on already. Returns `{ kind: 'app' | 'whole' |
251
+ * 'none', state }`.
252
+ */
253
+ async function followNavigation(world, before, sameAddress) {
254
+ const result = await poll(world, (s) => {
255
+ if (!s) return { done: false };
256
+ if (s.doc !== before.doc) {
257
+ const ready = s.readyState === 'complete' && (!s.app || !s.js || s.wired);
258
+ return { done: ready && s.still, kind: 'whole', state: s };
259
+ }
260
+ const ended = s.nav.ends > before.nav.ends && !s.nav.pending;
261
+ const moved = s.route !== before.route || s.url !== before.url;
262
+ const announced = s.announcer === null || norm(s.announcer) === norm(s.title);
263
+ if (moved || ended || sameAddress) return { done: (moved || sameAddress || ended) && !s.nav.pending && announced && s.still, kind: 'app', state: s };
264
+ return { done: false, kind: 'none', state: s };
265
+ }, budget(world));
266
+ const kind = result.done ? result.kind : 'none';
267
+ world.vueNavigation = { kind, from: before.url, to: result.state ? result.state.url : before.url, doc: result.state ? result.state.doc : before.doc, at: Date.now() };
268
+ return { kind, done: !!result.done, state: result.state || before };
269
+ }
270
+
271
+ module.exports = {
272
+ PROBE,
273
+ budget,
274
+ norm,
275
+ listed,
276
+ excerpt,
277
+ sleep,
278
+ ensureProbe,
279
+ call,
280
+ pageState,
281
+ poll,
282
+ lane,
283
+ laneFailure,
284
+ wiredUp,
285
+ beforeActing,
286
+ note,
287
+ still,
288
+ escapeRe,
289
+ byRoleAndName,
290
+ namesOf,
291
+ followNavigation,
292
+ failure: (page, message, details) => failure(page, message, details),
293
+ friendly: (input, cause) => friendly(input, cause),
294
+ };
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ // The page and its waits: the app wiring the server's page up, a page drawn in the browser only, the
4
+ // page being still. The waits of every other step of the pack build on these.
5
+
6
+ const { Given, When, Then, AfterStep } = require('@cucumber/cucumber');
7
+ const h = require('./vue-helpers');
8
+
9
+ /**
10
+ * Wait for the app to wire the page up. A Nuxt page arrives as the server's HTML, and the app's scripts
11
+ * then make it the app's in the browser (hydration): until then its links load whole pages and its
12
+ * buttons do nothing yet. The sign is the app's own state: Nuxt no longer hydrating, or a Vue app
13
+ * mounted. A page without an app, or a browser without JavaScript, has nothing to wait for: the step
14
+ * goes on, and the run's log says so.
15
+ *
16
+ * Example #1: Given the page is wired up
17
+ * Example #2: When the page is wired up
18
+ * Example #3: And the page is wired up
19
+ * Example #4: Then the page is wired up
20
+ * Example #5: But the page is wired up
21
+ */
22
+ Given(/^the page is wired up$/, async function () {
23
+ const w = await h.beforeActing(this);
24
+ if (w.app && w.js && !w.wired) {
25
+ throw await h.laneFailure(this, 'Expected the app to wire the page up, but it did not.', {
26
+ found: `the page has the app's markup, and the app was not wired up in ${Math.round(h.budget(this) / 1000)} s`,
27
+ hint: 'the app may have failed to start: look at the browser errors of the run (a module that did not load, an error in a plugin or a page\'s setup).',
28
+ });
29
+ }
30
+ await h.still(this);
31
+ });
32
+
33
+ /**
34
+ * The app has wired the page up: the page has a Vue app (Nuxt's, or a mounted one), and it is no
35
+ * longer hydrating. Unlike "the page is wired up", it fails on a page without an app and in a browser
36
+ * without JavaScript.
37
+ *
38
+ * Example #1: Then the page should be wired up
39
+ * Example #2: And the page should be wired up
40
+ * Example #3: Then the page should be wired up
41
+ * Example #4: But the page should be wired up
42
+ * Example #5: Then the page should be wired up
43
+ */
44
+ Then(/^the page should be wired up$/, async function () {
45
+ const w = await h.wiredUp(this);
46
+ if (w.wired) return;
47
+ const s = w.state || {};
48
+ throw await h.laneFailure(this, !w.js
49
+ ? 'Expected the page to be wired up, but the browser has JavaScript off.'
50
+ : (!w.app ? 'Expected the page to be wired up, but the page has no app.' : 'Expected the page to be wired up, but the app has not wired it up.'), {
51
+ found: `${s.url || 'the page'}: ${s.nuxt ? 'a Nuxt page' : (s.app ? 'a Vue app\'s page' : 'no app\'s markup')}; route announcer: ${s.announcer === null || s.announcer === undefined ? 'none' : 'there'}`,
52
+ hint: w.app ? 'look at the browser errors of the run: a module that did not load, or an error while the app starts.' : 'the page has none of the markers of an app (Nuxt\'s #__nuxt, a mounted Vue app\'s data-v-app).',
53
+ });
54
+ });
55
+
56
+ /**
57
+ * The page was drawn in the browser only: the server's HTML held an empty element for the app (a route
58
+ * Nuxt renders on the client, `ssr: false`), and the app drew the page in it. Without JavaScript such a
59
+ * page stays empty.
60
+ *
61
+ * Example #1: Then the page should have been drawn in the browser only
62
+ * Example #2: And the page should have been drawn in the browser only
63
+ * Example #3: Then the page should have been drawn in the browser only
64
+ * Example #4: But the page should have been drawn in the browser only
65
+ * Example #5: Then the page should have been drawn in the browser only
66
+ */
67
+ Then(/^the page should have been drawn in the browser only$/, async function () {
68
+ const result = await h.poll(this, async (s) => {
69
+ if (!s || s.readyState === 'loading') return { done: false };
70
+ const shell = await h.call(this, 'shellOnly');
71
+ return { done: shell === true, shell, state: s };
72
+ }, h.budget(this));
73
+ if (result.done) return;
74
+ const s = result.state || {};
75
+ throw await h.laneFailure(this, 'Expected the page to have been drawn in the browser only, but the server\'s HTML held it.', {
76
+ found: `${s.url || 'the page'}: ${result.shell === false ? 'the server sent the page rendered' : 'no element for the app was found'}`,
77
+ hint: 'a route is drawn in the browser only when the app turns server rendering off for it (routeRules: { ssr: false }).',
78
+ });
79
+ });
80
+
81
+ /**
82
+ * Wait for the page to be still: no page load in progress, no request in flight, no navigation of the
83
+ * app in progress, no frame asked for, no animation or transition running, the page wired up when it
84
+ * can be, and nothing changed for two frames.
85
+ *
86
+ * Example #1: When I wait for the page to be still
87
+ * Example #2: And I wait for the page to be still
88
+ * Example #3: When we wait for the page to be still
89
+ * Example #4: Then I wait for the page to be still
90
+ * Example #5: Given I wait for the page to be still
91
+ */
92
+ When(/^(?:I |we )?wait for the page to be still$/, async function () {
93
+ const result = await h.still(this, h.budget(this));
94
+ if (result.done) return;
95
+ const s = result.state || {};
96
+ throw await h.laneFailure(this, `Expected the page to be still, but it was still busy after ${Math.round(h.budget(this) / 1000)} s.`, {
97
+ found: (s.busy || []).join('; ') || 'the page was between two documents',
98
+ hint: 'an animation without an end, or a request that never answers, keeps a page busy: wait for what a person waits for instead (a text, a field).',
99
+ });
100
+ });
101
+
102
+ // Opt in with the tag @still-after-steps: after every step of the scenario (webship-js's own
103
+ // `I press "…"`, `I click "…"` too), wait for the page to be still, on a page with an app. It never
104
+ // fails a step: what comes next waits for what it expects anyway.
105
+ AfterStep({ tags: '@still-after-steps' }, async function () {
106
+ if (!this.page) return;
107
+ const s = await h.pageState(this);
108
+ if (s && s.app) await h.still(this);
109
+ });