@webship-js/nextjs-steps 0.0.0-stage → 2.0.1

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,200 @@
1
+ 'use strict';
2
+
3
+ // Images of the image component, found by their alternative text: lazy or
4
+ // preloaded, optimized by the app's image optimizer (sizes for each screen, a
5
+ // modern format), sized ahead of loading, loaded or not yet, and brought into
6
+ // view so that a lazy one loads.
7
+
8
+ const { Then, When } = require('@cucumber/cucumber');
9
+ const {
10
+ budget,
11
+ listed,
12
+ failure,
13
+ shortUrl,
14
+ siteUrl,
15
+ pageReady,
16
+ imageByAlt,
17
+ imageNames,
18
+ imageInfo,
19
+ optimizedAddress,
20
+ eventually,
21
+ } = require('./nextjs-helpers');
22
+
23
+ /** The image named by its alternative text, or a failure that lists the images of the page. */
24
+ async function theImage(world, alt) {
25
+ const image = await imageByAlt(world, alt);
26
+ if (!(await image.count())) {
27
+ throw failure(world, `Expected an image "${alt}" on ${shortUrl(world.page.url())}, but there is none. Images on the page: ${listed(await imageNames(world))}.`, 'An image is found by its alternative text (alt), as a screen reader names it.');
28
+ }
29
+ return image;
30
+ }
31
+
32
+ /**
33
+ * Whether the image loads lazily (loading="lazy": the browser fetches it when
34
+ * it comes near the window), as the image component makes every image that is
35
+ * not marked as a priority.
36
+ *
37
+ * Example #1: Then the image "Ivy Example's profile picture" should load lazily
38
+ * Example #2: And the image "logomark" should load lazily
39
+ * Example #3: Then the image "logo" should not load lazily
40
+ * Example #4: Then image "Screenshots of the dashboard project showing desktop version" should load lazily
41
+ * Example #5: And the image "Oak Example's profile picture" should load lazily
42
+ */
43
+ Then(/^(?:the )?image "([^"]*)?" should( not)* load lazily$/, async function (alt, notCase) {
44
+ await pageReady(this);
45
+ const info = await imageInfo(await theImage(this, alt));
46
+ const lazy = info.loading === 'lazy';
47
+ if (!notCase && !lazy) {
48
+ throw failure(this, `Expected the image "${alt}" to load lazily, but its loading is "${info.loading || 'eager (no loading attribute)'}".`, 'The image component makes an image lazy unless it is marked as a priority (preload, or loading="eager").');
49
+ }
50
+ if (notCase && lazy) {
51
+ throw failure(this, `Expected the image "${alt}" to load at once, but it loads lazily (loading="lazy").`, 'An image above the fold (a logo, a hero image) is marked as a priority so that it does not wait.');
52
+ }
53
+ });
54
+
55
+ /**
56
+ * Whether the page asks for the image ahead of time: a <link rel="preload"
57
+ * as="image"> for it in the head, as the image component adds for an image
58
+ * marked as a priority.
59
+ *
60
+ * Example #1: Then the image "logo" should be preloaded
61
+ * Example #2: And the image "logomark" should not be preloaded
62
+ * Example #3: Then image "logo" should be preloaded
63
+ * Example #4: Then the image "Ivy Example's profile picture" should not be preloaded
64
+ * Example #5: And the image "logo" should be preloaded
65
+ */
66
+ Then(/^(?:the )?image "([^"]*)?" should( not)* be preloaded$/, async function (alt, notCase) {
67
+ await pageReady(this);
68
+ const info = await imageInfo(await theImage(this, alt));
69
+ if (!notCase && !info.preloaded) {
70
+ throw failure(this, `Expected the image "${alt}" to be preloaded, but the page has no <link rel="preload" as="image"> for ${shortUrl(info.src)}.`, 'The image component preloads an image marked as a priority (the preload or priority property).');
71
+ }
72
+ if (notCase && info.preloaded) {
73
+ throw failure(this, `Expected the image "${alt}" not to be preloaded, but the page preloads ${shortUrl(info.src)}.`, 'Only the images that matter at first sight should be preloaded.');
74
+ }
75
+ });
76
+
77
+ /**
78
+ * Whether the image comes from the app's image optimizer (/_next/image),
79
+ * which sends a size made for the screen (the widths of its srcset) in a
80
+ * modern format. An SVG and an image marked as unoptimized come as they are.
81
+ *
82
+ * Example #1: Then the image "Ivy Example's profile picture" should be optimized
83
+ * Example #2: And the image "logo" should not be optimized
84
+ * Example #3: Then image "Screenshots of the dashboard project showing desktop version" should be optimized
85
+ * Example #4: Then the image "logomark" should not be optimized
86
+ * Example #5: And the image "Oak Example's profile picture" should be optimized
87
+ */
88
+ Then(/^(?:the )?image "([^"]*)?" should( not)* be optimized$/, async function (alt, notCase) {
89
+ await pageReady(this);
90
+ const info = await imageInfo(await theImage(this, alt));
91
+ const optimized = optimizedAddress(info.src) && (!info.srcset || info.srcset.split(',').every((part) => optimizedAddress(part.trim())));
92
+ if (!notCase && !optimized) {
93
+ throw failure(this, `Expected the image "${alt}" to come from the image optimizer, but its address is ${shortUrl(info.src)}${info.srcset ? ` (srcset ${shortUrl(info.srcset)})` : ''}.`, 'The image component sends an image through /_next/image unless it is an SVG, marked as unoptimized, or the app\'s config turns the optimizer off.');
94
+ }
95
+ if (notCase && optimized) {
96
+ throw failure(this, `Expected the image "${alt}" to come as it is, but it comes from the image optimizer (${shortUrl(info.src)}).`, 'An SVG, or an image marked as unoptimized, keeps its own address.');
97
+ }
98
+ });
99
+
100
+ /**
101
+ * The format the server sends the image in, for a browser that takes the
102
+ * modern formats: "image/webp" or "image/avif" from the image optimizer.
103
+ *
104
+ * Example #1: Then the image "Ivy Example's profile picture" should be served as "image/webp"
105
+ * Example #2: And the image "Screenshots of the dashboard project showing desktop version" should be served as "image/webp"
106
+ * Example #3: Then image "Oak Example's profile picture" should be served as "image/webp"
107
+ * Example #4: Then the image "logo" should be served as "image/svg+xml"
108
+ * Example #5: And the image "Ivy Example's profile picture" should be served as "image/webp"
109
+ */
110
+ Then(/^(?:the )?image "([^"]*)?" should be served as "([^"]*)?"$/, async function (alt, type) {
111
+ await pageReady(this);
112
+ const info = await imageInfo(await theImage(this, alt));
113
+ const address = info.currentSrc || info.src;
114
+ if (!address) {
115
+ throw failure(this, `Expected the image "${alt}" to have an address, but it has none.`, 'The image has no src or srcset.');
116
+ }
117
+ let served = '';
118
+ try {
119
+ const response = await this.page.context().request.get(siteUrl(this, address), {
120
+ headers: { accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8' },
121
+ failOnStatusCode: false,
122
+ });
123
+ served = String(response.headers()['content-type'] || '').split(';')[0].trim();
124
+ } catch (err) {
125
+ throw failure(this, `Could not ask for the image "${alt}" (${shortUrl(address)}): ${err.message}`, 'The step asks for the image the way the browser does.');
126
+ }
127
+ if (served !== type) {
128
+ throw failure(this, `Expected the image "${alt}" to be served as ${type}, but it is served as ${served || 'no type'} (${shortUrl(address)}).`, 'The image optimizer sends the first of the formats of images.formats in next.config (WebP by default) that the browser takes.');
129
+ }
130
+ });
131
+
132
+ /**
133
+ * Whether the image has a width and a height before it loads, so the page
134
+ * keeps its place and does not shift (as the image component asks for).
135
+ *
136
+ * Example #1: Then the image "Ivy Example's profile picture" should have a width and a height
137
+ * Example #2: And the image "logo" should have a width and a height
138
+ * Example #3: Then image "logomark" should have a width and a height
139
+ * Example #4: Then the image "Screenshots of the dashboard project showing desktop version" should have a width and a height
140
+ * Example #5: And the image "Oak Example's profile picture" should have a width and a height
141
+ */
142
+ Then(/^(?:the )?image "([^"]*)?" should have a width and a height$/, async function (alt) {
143
+ await pageReady(this);
144
+ const image = await theImage(this, alt);
145
+ const size = await image.evaluate((img) => ({
146
+ width: img.getAttribute('width') || '',
147
+ height: img.getAttribute('height') || '',
148
+ fill: img.getAttribute('data-nimg') === 'fill',
149
+ }));
150
+ if (!size.fill && (!size.width || !size.height)) {
151
+ throw failure(this, `Expected the image "${alt}" to have a width and a height, but it has width "${size.width}" and height "${size.height}".`, 'Without them the page moves when the image arrives (layout shift); the image component needs them unless the image fills its container.');
152
+ }
153
+ });
154
+
155
+ /**
156
+ * Whether the browser has fetched and decoded the image. A lazy image out of
157
+ * the window has not loaded yet; "should have loaded" waits for it.
158
+ *
159
+ * Example #1: Then the image "Ivy Example's profile picture" should have loaded
160
+ * Example #2: And the image "Screenshot of the dashboard project showing mobile version" should not have loaded
161
+ * Example #3: Then image "logomark" should have loaded
162
+ * Example #4: Then the image "Oak Example's profile picture" should not have loaded
163
+ * Example #5: And the image "logo" should have loaded
164
+ */
165
+ Then(/^(?:the )?image "([^"]*)?" should( not)* have loaded$/, async function (alt, notCase) {
166
+ await pageReady(this);
167
+ const image = await theImage(this, alt);
168
+ const loaded = (info) => info.complete && info.naturalWidth > 0;
169
+ if (notCase) {
170
+ const info = await imageInfo(image);
171
+ if (loaded(info)) {
172
+ throw failure(this, `Expected the image "${alt}" not to have loaded yet, but the browser has it (${shortUrl(info.currentSrc)}).`, 'A lazy image loads when it comes near the window; a hidden one (display: none) never loads.');
173
+ }
174
+ return;
175
+ }
176
+ await eventually(this, () => imageInfo(image), loaded, (info) => ({
177
+ message: `Expected the image "${alt}" to have loaded, but it has not (${info.visible ? 'it is on the page' : 'it is hidden'}, loading "${info.loading || 'eager'}", address ${shortUrl(info.currentSrc || info.src) || 'none yet'}).`,
178
+ hint: info.loading === 'lazy' && info.visible ? 'A lazy image loads when it comes near the window: bring it into view first ("When I scroll the image "…" into view").' : 'Check that its address answers 200.',
179
+ }), budget(this));
180
+ });
181
+
182
+ /**
183
+ * Bring the image to the middle of the window, as a person scrolling to it
184
+ * does, and wait for it to load (a lazy image loads only then).
185
+ *
186
+ * Example #1: When I scroll the image "Oak Example's profile picture" into view
187
+ * Example #2: And we scroll the image "Ivy Example's profile picture" into view
188
+ * Example #3: When I scroll the image "logomark" into view
189
+ * Example #4: When I scroll the image "Ivy Example's profile picture" into view
190
+ * Example #5: And I scroll the image "Oak Example's profile picture" into view
191
+ */
192
+ When(/^(I |we )*scroll the image "([^"]*)?" into view$/, async function (pronounCase, alt) {
193
+ await pageReady(this);
194
+ const image = await theImage(this, alt);
195
+ await image.evaluate((img) => img.scrollIntoView({ block: 'center', inline: 'nearest' }));
196
+ await eventually(this, () => imageInfo(image), (info) => info.complete && info.naturalWidth > 0, (info) => ({
197
+ message: `Expected the image "${alt}" to load once in view, but it has not (${info.visible ? 'on the page' : 'hidden'}, address ${shortUrl(info.currentSrc || info.src) || 'none'}).`,
198
+ hint: 'A hidden image (display: none) never loads; check also that its address answers 200.',
199
+ }), budget(this));
200
+ });
@@ -0,0 +1,170 @@
1
+ 'use strict';
2
+
3
+ // Streaming and loading states: the parts of a page that show their loading
4
+ // state while the server streams their content, a slow network that makes
5
+ // them visible, answers of the app held back to see what a page does while it
6
+ // waits (a pending navigation, a pending form), and a page load that does not
7
+ // wait for the end of the stream.
8
+
9
+ const { After, Given, Then, When } = require('@cucumber/cucumber');
10
+ const { gotoUrl } = require('webship-js/tests/step-definitions/webship');
11
+ const {
12
+ budget,
13
+ failure,
14
+ shortUrl,
15
+ siteUrl,
16
+ pendingWork,
17
+ pageReady,
18
+ runningRequests,
19
+ holdAnswers,
20
+ releaseAnswers,
21
+ slowNetwork,
22
+ eventually,
23
+ } = require('./nextjs-helpers');
24
+
25
+ // Answers held back at the end of a scenario are let go, so the browser can close.
26
+ After(async function () {
27
+ if (this.__heldAnswers) await releaseAnswers(this).catch(() => {});
28
+ });
29
+
30
+ /** The parts of the page that show their loading state, as pendingWork reports them. */
31
+ async function loadingParts(world) {
32
+ const busy = await pendingWork(world);
33
+ return busy.split('; ').filter((part) => /showing their loading state|still waiting for their content/.test(part));
34
+ }
35
+
36
+ /**
37
+ * A slow network for the page, as on a slow mobile connection: every answer
38
+ * comes slowly, so the parts the app streams arrive one after the other and
39
+ * their loading states stay on the screen long enough to be seen. Chromium
40
+ * only (its own network emulation). "is no longer slow" brings the speed back.
41
+ *
42
+ * Example #1: Given the network is slow
43
+ * Example #2: And the network is slow
44
+ * Example #3: When the network is no longer slow
45
+ * Example #4: Given network is slow
46
+ * Example #5: And the network is no longer slow
47
+ */
48
+ Given(/^(?:the )?network is (no longer )?slow$/, async function (noLonger) {
49
+ await slowNetwork(this, !noLonger);
50
+ });
51
+
52
+ /**
53
+ * Start loading a page of the app and return as soon as the server starts to
54
+ * answer, without waiting for the page to load: for the scenarios that look
55
+ * at a page while its parts still stream in (a slow network shows them).
56
+ *
57
+ * Example #1: When I start to go to "/dashboard/invoices"
58
+ * Example #2: And we start to go to "/dashboard"
59
+ * Example #3: When I start to go to "/dashboard/customers"
60
+ * Example #4: When I start to go to "/"
61
+ * Example #5: And I start to go to "/dashboard/invoices?page=2"
62
+ */
63
+ When(/^(I |we )*start to go to "([^"]*)?"$/, { timeout: 60000 }, async function (pronounCase, path) {
64
+ const url = siteUrl(this, path);
65
+ try {
66
+ await this.page.goto(url, { waitUntil: 'commit', timeout: budget(this) * 2 });
67
+ } catch (err) {
68
+ if (!/ERR_NETWORK_CHANGED/.test(String(err && err.message))) throw failure(this, `Could not start to load ${url}: ${err.message}`, 'Check launchUrl in cucumber.js and that the app answers.');
69
+ await gotoUrl(this.page, url);
70
+ }
71
+ });
72
+
73
+ /**
74
+ * Whether a part of the page shows its loading state: a part the server
75
+ * streamed that still waits for its content (the HTML's own markers), or a
76
+ * Suspense boundary of the app showing its fallback (a skeleton, a spinner, a
77
+ * loading.js page). "a part … should show" waits for one to appear; "no part
78
+ * … should show" waits for every one to be replaced by its content.
79
+ *
80
+ * Example #1: Then a part of the page should show its loading state
81
+ * Example #2: Then no part of the page should show its loading state
82
+ * Example #3: And a part of the page should show its loading state
83
+ * Example #4: And no part of the page should show its loading state
84
+ * Example #5: But no part of the page should show its loading state
85
+ */
86
+ Then(/^(a|no) part of the page should show its loading state$/, { timeout: 60000 }, async function (which) {
87
+ if (which === 'a') {
88
+ await eventually(this, () => loadingParts(this), (parts) => parts.length > 0, () => ({
89
+ message: `Expected a part of the page to show its loading state, but none did within ${budget(this)} ms (${this.page.url()}).`,
90
+ hint: 'A part shows its loading state only while its content is on the way: on a fast network it can be over before the step looks. Slow the network down first ("Given the network is slow"), or hold the app\'s answers back.',
91
+ }), budget(this) * 2);
92
+ return;
93
+ }
94
+ await eventually(this, () => loadingParts(this), (parts) => parts.length === 0, (parts) => ({
95
+ message: `Expected no part of the page to show its loading state, but ${parts.join('; ')} after ${budget(this) * 3} ms (${this.page.url()}).`,
96
+ hint: 'A part stays in its loading state while the server has not sent its content: a slow query, an answer held back, or an error on the server (look at the server log).',
97
+ }), budget(this) * 3);
98
+ });
99
+
100
+ /**
101
+ * Hold back the app's answers from here on: the payload of a navigation, a
102
+ * form action and the data of a page wait until "the server's answers come
103
+ * through". For the scenarios that look at what a page shows while it waits:
104
+ * the page it keeps, a form that says it is busy.
105
+ *
106
+ * Example #1: Given the server's answers are held back
107
+ * Example #2: And the server's answers are held back
108
+ * Example #3: When the server's answers are held back
109
+ * Example #4: Given server's answers are held back
110
+ * Example #5: And the server's answers are held back
111
+ */
112
+ Given(/^(?:the )?server's answers are held back$/, async function () {
113
+ await holdAnswers(this);
114
+ });
115
+
116
+ /**
117
+ * Let the answers held back go, and wait for the page to be ready with them.
118
+ *
119
+ * Example #1: When the server's answers come through
120
+ * Example #2: And the server's answers come through
121
+ * Example #3: Then the server's answers come through
122
+ * Example #4: When server's answers come through
123
+ * Example #5: And the server's answers come through
124
+ */
125
+ When(/^(?:the )?server's answers come through$/, { timeout: 60000 }, async function () {
126
+ const held = await releaseAnswers(this);
127
+ if (!held) {
128
+ throw failure(this, 'Expected answers of the server held back, but none were: "Given the server\'s answers are held back" comes first.', 'Hold the answers back before the action whose answer the scenario waits for.');
129
+ }
130
+ await pageReady(this, { strict: true });
131
+ });
132
+
133
+ /**
134
+ * Whether the page waits for the server: a request it needs is on the way (a
135
+ * navigation's payload, a form action, a page's data, a request of the app).
136
+ * "should be" waits for one to start; "should not be" for every one to end.
137
+ *
138
+ * Example #1: Then the page should be waiting for the server
139
+ * Example #2: And the page should be waiting for the server
140
+ * Example #3: Then the page should not be waiting for the server
141
+ * Example #4: Then page should be waiting for the server
142
+ * Example #5: And the page should not be waiting for the server
143
+ */
144
+ Then(/^(?:the )?page should( not)* be waiting for the server$/, { timeout: 60000 }, async function (notCase) {
145
+ if (notCase) {
146
+ await eventually(this, () => runningRequests(this.page), (running) => running.length === 0, (running) => ({
147
+ message: `Expected the page not to wait for the server, but ${running.length} request(s) still run: ${running.slice(0, 3).map((r) => `${r.kind} ${shortUrl(r.url)}`).join(', ')}.`,
148
+ hint: this.__heldAnswers ? 'The answers are held back: "When the server\'s answers come through" lets them go.' : 'A request that never ends is a fault of the app or of its server.',
149
+ }), budget(this) * 2);
150
+ return;
151
+ }
152
+ await eventually(this, () => runningRequests(this.page), (running) => running.some((r) => r.kind !== 'background'), () => ({
153
+ message: `Expected the page to wait for the server, but no request of a navigation, a form or a page's data is on the way (${this.page.url()}).`,
154
+ hint: this.__heldAnswers ? 'The action before this step sent no request: a page the router had fetched ahead of the click shows at once.' : 'Hold the answers back first ("Given the server\'s answers are held back"): on a local app the answer comes before the step looks.',
155
+ }));
156
+ });
157
+
158
+ /**
159
+ * Wait until the page is ready; the alias a scenario reads after a page that
160
+ * streams, where "finished loading" is what a person says.
161
+ *
162
+ * Example #1: When I wait for the page to finish loading
163
+ * Example #2: And we wait for the page to finish loading
164
+ * Example #3: Then I wait for the page to finish loading
165
+ * Example #4: When we wait for the page to finish loading
166
+ * Example #5: And I wait for the page to finish loading
167
+ */
168
+ When(/^(I |we )*wait for the page to finish loading$/, { timeout: 120000 }, async function (pronounCase) {
169
+ await pageReady(this, { strict: true, timeout: budget(this) * 6 });
170
+ });
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+
3
+ // Client-side navigation: a link followed and the browser's back and forward
4
+ // buttons, each without a full page reload; the route announcer that tells a
5
+ // screen reader about the new page; and the pages the router fetches ahead of
6
+ // a click.
7
+
8
+ const { Then, When } = require('@cucumber/cucumber');
9
+ const {
10
+ budget,
11
+ clean,
12
+ same,
13
+ listed,
14
+ failure,
15
+ pathOf,
16
+ shortUrl,
17
+ requests,
18
+ documentId,
19
+ appInfo,
20
+ pageReady,
21
+ afterAction,
22
+ waitHydrated,
23
+ linkByName,
24
+ firstPresent,
25
+ visibleLinkNames,
26
+ announcer,
27
+ eventually,
28
+ } = require('./nextjs-helpers');
29
+
30
+ /**
31
+ * The address a link leads to, as the browser resolves it.
32
+ */
33
+ async function linkTarget(locator) {
34
+ return locator.evaluate((a) => a.href || '').catch(() => '');
35
+ }
36
+
37
+ /**
38
+ * Wait for a client-side navigation to finish: the page is ready and its
39
+ * document is the one it was before (no full page reload).
40
+ */
41
+ async function finishWithoutReload(world, before, what) {
42
+ await pageReady(world);
43
+ const after = await documentId(world);
44
+ if (!after || after !== before) {
45
+ throw failure(world, `Expected ${what} without a full page reload, but the browser loaded a new document (${world.page.url()}).`, 'The router handles a click on one of its links in the page: a full reload means the link is a plain <a> (not the framework\'s Link), the page was not hydrated yet, or the router fell back to a hard navigation after an error.');
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Click a link by its name and let the router show the new page in the same
51
+ * document: the step waits for the link to be hydrated, then for the
52
+ * navigation to finish, and fails if the browser loaded a new document.
53
+ *
54
+ * Example #1: When I click the link "Invoices" without a full page reload
55
+ * Example #2: And we click the link "Customers" without a full page reload
56
+ * Example #3: When I click the link "Home" without a full page reload
57
+ * Example #4: When I click the link "Users List" without a full page reload
58
+ * Example #5: And I click the link "About" without a full page reload
59
+ */
60
+ When(/^(I |we )*click the link "([^"]*)?" without a full page reload$/, { timeout: 60000 }, async function (pronounCase, name) {
61
+ await pageReady(this);
62
+ const { exact, loose } = linkByName(this, name);
63
+ const link = await firstPresent([exact, loose]);
64
+ if (!(await link.count())) {
65
+ throw failure(this, `Expected a link "${name}" on ${this.page.url()}, but there is none. Links on the page: ${listed(await visibleLinkNames(this))}.`, 'A link is found by the name a person reads: its text or its accessible name (aria-label).');
66
+ }
67
+ await waitHydrated(this, link, `the link "${name}"`);
68
+ const target = await linkTarget(link);
69
+ const before = await documentId(this);
70
+ await afterAction(this, async () => {
71
+ await link.evaluate((a) => a.scrollIntoView({ block: 'center', inline: 'nearest' })).catch(() => {});
72
+ await link.click({ timeout: budget(this) });
73
+ });
74
+ if (target) {
75
+ await eventually(this, () => this.page.url(), (url) => pathOf(url) === pathOf(target), (url) => ({
76
+ message: `Expected the link "${name}" to lead to ${shortUrl(target)}, but the page is still ${shortUrl(url)} after ${budget(this)} ms.`,
77
+ hint: 'The router changes the address when the new page is ready to show; a request that never answers keeps the old page.',
78
+ }));
79
+ }
80
+ await finishWithoutReload(this, before, `the link "${name}" to open its page`);
81
+ });
82
+
83
+ /**
84
+ * Go back (or forward) one page with the browser's own button, the router
85
+ * showing that page again in the same document.
86
+ *
87
+ * Example #1: When I go back without a full page reload
88
+ * Example #2: And we go back without a full page reload
89
+ * Example #3: When I go forward without a full page reload
90
+ * Example #4: And I go forward without a full page reload
91
+ * Example #5: When we go forward without a full page reload
92
+ */
93
+ When(/^(I |we )*go (back|forward) without a full page reload$/, { timeout: 60000 }, async function (pronounCase, direction) {
94
+ await pageReady(this);
95
+ const before = await documentId(this);
96
+ const from = this.page.url();
97
+ await afterAction(this, async () => {
98
+ if (direction === 'back') await this.page.goBack({ waitUntil: 'commit', timeout: budget(this) }).catch(() => null);
99
+ else await this.page.goForward({ waitUntil: 'commit', timeout: budget(this) }).catch(() => null);
100
+ });
101
+ if (this.page.url() === from) {
102
+ throw failure(this, `Expected going ${direction} to change the page, but it is still ${shortUrl(from)}.`, `The history of the browser has no page ${direction === 'back' ? 'before' : 'after'} this one in this scenario.`);
103
+ }
104
+ await finishWithoutReload(this, before, `going ${direction}`);
105
+ });
106
+
107
+ /**
108
+ * The route announcer: the live region the router fills with the title of
109
+ * each new page (an empty region after the first load, as a screen reader
110
+ * reads that page itself).
111
+ *
112
+ * Example #1: Then the page should have a route announcer
113
+ * Example #2: And page should have a route announcer
114
+ * Example #3: Then the page should not have a route announcer
115
+ * Example #4: Then the page should have a route announcer
116
+ * Example #5: And the page should have a route announcer
117
+ */
118
+ Then(/^(?:the )?page should( not)* have a route announcer$/, async function (notCase) {
119
+ await pageReady(this);
120
+ const state = await announcer(this);
121
+ if (!notCase && !state.present) {
122
+ throw failure(this, `Expected a route announcer on ${this.page.url()}, but the page has none.`, 'The router puts it on every page it serves (#__next-route-announcer__ in the next-route-announcer element); a page the framework does not serve has none.');
123
+ }
124
+ if (notCase && state.present) {
125
+ throw failure(this, `Expected no route announcer on ${this.page.url()}, but the page has one (aria-live="${state.live}").`, 'The router puts one on every page it serves.');
126
+ }
127
+ });
128
+
129
+ /**
130
+ * What the route announcer says: the title of the page the router just
131
+ * showed, or its start (the words before the rest of a title template:
132
+ * "Invoices" for "Invoices | Acme Dashboard"); letter case and white space
133
+ * ignored.
134
+ *
135
+ * Example #1: Then the route announcer should announce "Invoices | Acme Dashboard"
136
+ * Example #2: And route announcer should announce "Customers | Acme Dashboard"
137
+ * Example #3: Then the route announcer should not announce "Invoices | Acme Dashboard"
138
+ * Example #4: Then the route announcer should announce "Users List"
139
+ * Example #5: And the route announcer should announce "About"
140
+ */
141
+ Then(/^(?:the )?route announcer should( not)* announce "([^"]*)?"$/, async function (notCase, text) {
142
+ await pageReady(this);
143
+ if (notCase) {
144
+ const state = await announcer(this);
145
+ if (state.present && (same(state.text, text) || state.text.toLowerCase().startsWith(`${clean(text).toLowerCase()} `))) {
146
+ throw failure(this, `Expected the route announcer not to announce "${text}", but it does.`, 'It announces the title of the last page the router showed.');
147
+ }
148
+ return;
149
+ }
150
+ // The whole announcement, or its start: "Invoices" for "Invoices | Acme Dashboard" (a title template).
151
+ const says = (state) => state.present && (same(state.text, text) || state.text.toLowerCase().startsWith(`${clean(text).toLowerCase()} `));
152
+ await eventually(this, () => announcer(this), says, (state) => ({
153
+ message: state.present
154
+ ? `Expected the route announcer to announce "${text}", but it announces "${state.text}".`
155
+ : `Expected the route announcer to announce "${text}", but the page has no route announcer.`,
156
+ hint: 'The router announces the document title of the new page (else its first heading, else its path) after a client-side navigation; the first page of a visit is announced by the screen reader itself, so the region starts empty.',
157
+ }));
158
+ });
159
+
160
+ /**
161
+ * The router fetched a page ahead of a click (a link of it in the window): the
162
+ * App Router fetches the page's payload (header next-router-prefetch), the
163
+ * Pages Router its data or its code. Production builds prefetch; the
164
+ * development server does not.
165
+ *
166
+ * Example #1: Then the page "/dashboard/invoices" should be prefetched
167
+ * Example #2: And the page "/dashboard/customers" should be prefetched
168
+ * Example #3: Then the page "/login" should not be prefetched
169
+ * Example #4: Then page "/users" should be prefetched
170
+ * Example #5: And the page "/about" should be prefetched
171
+ */
172
+ Then(/^(?:the )?page "([^"]*)?" should( not)* be prefetched$/, async function (path, notCase) {
173
+ await pageReady(this);
174
+ const wanted = pathOf(path);
175
+ const state = requests(this.page);
176
+ // The page a prefetch was for: the path of an App Router payload, or the page of a Pages Router data file.
177
+ const pageOf = (url) => {
178
+ const p = pathOf(url);
179
+ if (!p.startsWith('/_next/data/')) return p;
180
+ return p.replace(/^\/_next\/data\/[^/]+/, '').replace(/\.json$/, '').replace(/\/index$/, '') || '/';
181
+ };
182
+ const read = async () => state.prefetched.some((url) => pageOf(url) === wanted);
183
+ if (notCase) {
184
+ if (await read()) {
185
+ throw failure(this, `Expected the page "${path}" not to be prefetched, but the router fetched it ahead of a click.`, 'A link with prefetch={false}, or the development server, does not prefetch.');
186
+ }
187
+ return;
188
+ }
189
+ const info = await appInfo(this);
190
+ await eventually(this, read, (ok) => ok, () => ({
191
+ message: `Expected the page "${path}" to be prefetched, but the router did not fetch it ahead of a click within ${budget(this)} ms. Pages it fetched: ${listed(state.prefetched.map(shortUrl).slice(-8))}.`,
192
+ hint: info.development ? 'The development server does not prefetch: run a production build.' : 'The router prefetches the pages of the links in the window, in a production build: is a link to that page visible, and is it the framework\'s Link?',
193
+ }));
194
+ });