@webship-js/codeigniter-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,217 @@
1
+ 'use strict';
2
+
3
+ // Forms as a person reads them: a field filled with a value of an account of
4
+ // the users registry (so no feature writes a password), the messages a page
5
+ // shows after a form or a redirect (errors, successes, warnings, information),
6
+ // a field the browser refuses as empty, and a form whose security token is
7
+ // out of date.
8
+ //
9
+ // The text, the clicks and the plain filling of fields are webship-js's own
10
+ // steps (I fill in, I press, I click the "..." button, I should see): this file
11
+ // adds only what the app decides.
12
+
13
+ const { When, Then } = require('@cucumber/cucumber');
14
+ const { friendly } = require('webship-js/tests/step-definitions/webship');
15
+ const {
16
+ budget,
17
+ clean,
18
+ listed,
19
+ eventually,
20
+ resolveUser,
21
+ findField,
22
+ fillLikeABuiltIn,
23
+ pageMessages,
24
+ } = require('./codeigniter-helpers');
25
+
26
+ const PARTS = { email: 'email', 'email address': 'email', username: 'username', 'user name': 'username', password: 'password' };
27
+
28
+ /** A part of an account of the registry: its address, its user name or its password. */
29
+ function accountPart(world, part, handle) {
30
+ const user = resolveUser(world, handle);
31
+ const key = PARTS[String(part).toLowerCase()];
32
+ const value = user[key];
33
+ if (!value) {
34
+ throw friendly({
35
+ message: `The user "${handle}" has no ${part} in the users registry.`,
36
+ hint: `Set worldParameters.users.${handle}.${key} in cucumber.js.`,
37
+ });
38
+ }
39
+ return value;
40
+ }
41
+
42
+ /**
43
+ * Fill in a field with the address, the user name or the password of an
44
+ * account of the users registry, so a feature never writes a password and runs
45
+ * against an app whose accounts have other names. The field is found as
46
+ * webship-js's "I fill in" finds it: by its label, placeholder or name,
47
+ * exactly as written.
48
+ *
49
+ * Example #1: When I fill in "Password" with the password of "user"
50
+ * Example #2: When we fill in "Email Address" with the email of "user"
51
+ * Example #3: And I fill in "Username" with the username of "admin"
52
+ * Example #4: When I fill in "email" with the email address of "developer"
53
+ * Example #5: And we fill in "Password (again)" with the password of "user"
54
+ */
55
+ When(/^(I |we )*fill in "([^"]*)" with the (email|email address|username|user name|password) of "([^"]*)"$/, async function (pronounCase, field, part, handle) {
56
+ await fillLikeABuiltIn(this, field, accountPart(this, part, handle));
57
+ });
58
+
59
+ /**
60
+ * Assert that a field holds the address or the user name of an account of the
61
+ * users registry: a form the app refused gives back what was typed in it.
62
+ *
63
+ * Example #1: Then the "Email Address" field should hold the email of "user"
64
+ * Example #2: Then the "Username" field should hold the username of "user"
65
+ * Example #3: And the "email" field should hold the email address of "admin"
66
+ * Example #4: Then the "Email Address" field should hold the email of "developer"
67
+ * Example #5: And the "username" field should hold the user name of "admin"
68
+ */
69
+ Then(/^the "([^"]*)" field should hold the (email|email address|username|user name) of "([^"]*)"$/, async function (field, part, handle) {
70
+ const wanted = accountPart(this, part, handle);
71
+ const control = await findField(this, field);
72
+ await eventually(this, () => control.inputValue().catch(() => ''), (value) => value === wanted, (value) => ({
73
+ message: `Expected the "${field}" field to hold the ${part} of "${handle}" ("${wanted}"), but it holds "${value}".`,
74
+ hint: 'A form the app refused comes back with what was typed in it, the passwords left out.',
75
+ }));
76
+ });
77
+
78
+ /** The messages of a kind on the page, as lines. */
79
+ async function messagesOf(world, kind) {
80
+ return (await pageMessages(world)).filter((m) => m.kind === kind).map((m) => m.text);
81
+ }
82
+
83
+ /** A line of a message box says the text: it is the text, or holds it. */
84
+ function says(lines, text) {
85
+ const wanted = clean(text);
86
+ return lines.some((line) => line === wanted || line.includes(wanted));
87
+ }
88
+
89
+ /**
90
+ * Assert a message the page shows, by its kind: an error ("Unable to log you
91
+ * in. Please check your password."), a success ("You have successfully logged
92
+ * out."), a warning or an information. The message is a line of a message box
93
+ * of the page (`role="alert"` or `role="status"`, marked by its kind: an
94
+ * `alert-danger` box is an error, `alert-success` a success); a box that
95
+ * lists several errors (a refused form) holds one per line. The step waits
96
+ * for the message, so it holds right after the press that sent the form.
97
+ *
98
+ * Example #1: Then I should see the error message "Unable to log you in. Please check your password."
99
+ * Example #2: Then I should see the success message "You have successfully logged out."
100
+ * Example #3: And I should see the error message "The Email Address field must contain a unique value."
101
+ * Example #4: Then we should not see the error message "Unable to log you in. Please check your credentials."
102
+ * Example #5: Then I should see the warning message "Your session will end in five minutes."
103
+ */
104
+ Then(/^(I |we )*should( not)* see the (error|success|warning|info) message "([^"]*)"$/, async function (pronounCase, notCase, kind, text) {
105
+ if (notCase) {
106
+ const lines = await messagesOf(this, kind);
107
+ if (says(lines, text)) {
108
+ throw friendly({ message: `Expected not to see the ${kind} message "${text}", but the page shows it (${this.page.url()}).`, hint: 'The page shows a message after a form it refused or an action it did.' });
109
+ }
110
+ return;
111
+ }
112
+ try {
113
+ await eventually(this, () => messagesOf(this, kind), (lines) => says(lines, text), () => ({ message: 'no match' }), budget(this));
114
+ } catch {
115
+ const all = await pageMessages(this);
116
+ const same = all.filter((m) => m.kind === kind).map((m) => m.text);
117
+ const others = all.filter((m) => m.kind !== kind).map((m) => `${m.kind}: "${m.text}"`);
118
+ throw friendly({
119
+ message: `Expected the ${kind} message "${text}" (${this.page.url()}). ${same.length ? `The ${kind} messages: ${listed(same)}.` : `The page shows no ${kind} message.`}${others.length ? ` Other messages: ${others.join(', ')}.` : ''}`,
120
+ hint: `A message is a line of a message box of the page (role="alert" or role="status"); its kind comes from the box (an "alert-danger" box holds errors, "alert-success" successes).`,
121
+ });
122
+ }
123
+ });
124
+
125
+ /**
126
+ * Assert that the page shows no message of a kind at all: no error after a
127
+ * form the app took, no success after one it refused.
128
+ *
129
+ * Example #1: Then I should not see any error message
130
+ * Example #2: And we should not see any success message
131
+ * Example #3: Then I should not see any error messages
132
+ * Example #4: But I should not see any warning message
133
+ * Example #5: Then we should not see any info message
134
+ */
135
+ Then(/^(I |we )*should not see any (error|success|warning|info) messages?$/, async function (pronounCase, kind) {
136
+ const lines = await messagesOf(this, kind);
137
+ if (lines.length) {
138
+ throw friendly({ message: `Expected no ${kind} message, but the page shows: ${listed(lines)} (${this.page.url()}).`, hint: 'The page shows a message after a form it refused or an action it did.' });
139
+ }
140
+ });
141
+
142
+ /**
143
+ * Assert that the browser refused to send a form because a required field is
144
+ * empty, naming the field: the form stays on screen and no request is made.
145
+ * The field is the one a person reads by that label (or its name).
146
+ *
147
+ * Example #1: Then the "Username" field should block submission as required
148
+ * Example #2: And the "Email Address" field should block submission as required
149
+ * Example #3: Then the "Password" field should block submission as required
150
+ * Example #4: And the "Password (again)" field should block submission as required
151
+ * Example #5: Then the "email" field should block submission as required
152
+ */
153
+ Then(/^the "([^"]*)" field should block submission as required$/, async function (label) {
154
+ const invalid = await this.page.evaluate(() => {
155
+ const norm = (s) => (s || '').replace(/\s+/g, ' ').trim();
156
+ const labelOf = (el) => {
157
+ const by = (el.getAttribute('aria-labelledby') || '').split(/\s+/).map((id) => document.getElementById(id)).filter(Boolean);
158
+ if (by.length) return norm(by.map((n) => n.textContent).join(' '));
159
+ if (el.labels && el.labels[0]) return norm(el.labels[0].textContent);
160
+ return norm(el.getAttribute('aria-label') || el.name || '');
161
+ };
162
+ const found = [];
163
+ for (const form of document.forms) {
164
+ if (form.noValidate) continue;
165
+ for (const el of form.elements) {
166
+ if (!el.willValidate || el.checkValidity()) continue;
167
+ found.push({ label: labelOf(el), name: el.name || '', missing: el.validity.valueMissing, message: el.validationMessage });
168
+ }
169
+ }
170
+ return found;
171
+ });
172
+ if (!invalid.length) {
173
+ throw friendly({
174
+ message: 'Expected the form to be blocked by an empty required field, but every field of the forms on the page passes the browser\'s checks.',
175
+ hint: 'A form with the "novalidate" attribute is checked by the server instead: assert its error message with the "I should see the error message ..." step.',
176
+ });
177
+ }
178
+ const wanted = label.trim().toLowerCase();
179
+ const hit = invalid.find((field) => field.label.toLowerCase() === wanted || field.name.toLowerCase() === wanted)
180
+ || invalid.find((field) => field.label.toLowerCase().startsWith(wanted));
181
+ if (!hit || !hit.missing) {
182
+ throw friendly({
183
+ message: `Expected the "${label}" field to block the form as empty. The fields the browser refuses: ${invalid.map((field) => `"${field.label || field.name}" (${field.message})`).join(', ')}.`,
184
+ hint: 'Leave the field empty and press the button that sends the form; the browser checks the required fields before it sends anything.',
185
+ });
186
+ }
187
+ });
188
+
189
+ /**
190
+ * Make the security token of the forms on the page out of date, as a form
191
+ * left open in a tab while the session behind it was renewed: the hidden
192
+ * field that carries the token (named like "csrf" or "token") gets a value the
193
+ * app never issued. Send the form next, and assert the refusal.
194
+ *
195
+ * Example #1: When the security token of the form expires
196
+ * Example #2: And the security token of the form expires
197
+ * Example #3: Given the security token of the form expires
198
+ * Example #4: When the security tokens of the forms expire
199
+ * Example #5: And the security tokens of the forms expire
200
+ */
201
+ When(/^the security tokens? of the forms? (?:expires|expire)$/, async function () {
202
+ const changed = await this.page.evaluate(() => {
203
+ const names = [];
204
+ for (const input of document.querySelectorAll('form input[type="hidden"]')) {
205
+ if (!/csrf|xsrf|token/i.test(input.name || '')) continue;
206
+ input.value = 'an-out-of-date-token-' + Date.now();
207
+ names.push(input.name);
208
+ }
209
+ return names;
210
+ });
211
+ if (!changed.length) {
212
+ throw friendly({
213
+ message: `No form of the page carries a security token (${this.page.url()}): no hidden field named like "csrf" or "token".`,
214
+ hint: 'Open a page with a form first (the login form, the registration form). A form without a token is not protected from forged requests.',
215
+ });
216
+ }
217
+ });