@webship-js/espocrm-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,377 @@
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 holds the plumbing the steps use and that
6
+ // another pack can require instead of copying: the wait budget, friendly errors, URL building, the users registry,
7
+ // logging in, the site's REST API as the managing user (for the test content a scenario makes and removes, and the
8
+ // cases the steps find by name), the site's fields (its pick lists, its look-up boxes), and the console lines the two
9
+ // refusals a suite asks for on purpose may leave.
10
+ //
11
+ // Everything here builds on webship-js's own helpers (`gotoUrl`, `waitForPageLoad`, `friendly`) so the steps behave
12
+ // like the core webship-js steps.
13
+
14
+ const { gotoUrl, waitForPageLoad, friendly } = require('webship-js/tests/step-definitions/webship');
15
+
16
+ /** The per-assertion wait budget: `minWaitTime.page` from cucumber.js, at least 10 seconds. */
17
+ function budget(world) {
18
+ return Math.max((world && world.minWaitTime && world.minWaitTime.page) || 0, 10000);
19
+ }
20
+
21
+ /** Escape a literal string for use in a RegExp. */
22
+ function escapeRegExp(text) {
23
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
24
+ }
25
+
26
+ /** A RegExp that matches the whole text (ignoring surrounding space and case). */
27
+ function exactly(text) {
28
+ return new RegExp('^\\s*' + escapeRegExp(text) + '\\s*$', 'i');
29
+ }
30
+
31
+ /** Collapse runs of white space and trim. */
32
+ function tidy(text) {
33
+ return String(text === null || text === undefined ? '' : text).replace(/\s+/g, ' ').trim();
34
+ }
35
+
36
+ /** Run an action and rethrow its failure as a friendly error. */
37
+ async function actOrExplain(label, target, fn, hint) {
38
+ try {
39
+ return await fn();
40
+ } catch (err) {
41
+ if (err && err.stack === err.message && /Hint:/.test(err.message)) throw err;
42
+ throw friendly({ action: label, target, cause: err, hint });
43
+ }
44
+ }
45
+
46
+ /** Poll a reader until its value satisfies a test, and return the last value read. */
47
+ async function waitForValue(read, test, timeout) {
48
+ const deadline = Date.now() + timeout;
49
+ let value;
50
+ for (;;) {
51
+ try { value = await read(); } catch { value = undefined; }
52
+ if (value !== undefined && test(value)) return { ok: true, value };
53
+ if (Date.now() >= deadline) return { ok: false, value };
54
+ await new Promise((resolve) => setTimeout(resolve, 300));
55
+ }
56
+ }
57
+
58
+ /** The site root without a trailing slash. */
59
+ function siteRoot(world) {
60
+ return String(world.launchUrl).replace(/\/+$/, '');
61
+ }
62
+
63
+ /** Join the site root and a path with exactly one slash. Absolute URLs pass through. */
64
+ function siteUrl(world, url) {
65
+ if (!url) return siteRoot(world);
66
+ if (/^https?:\/\//i.test(url)) return url;
67
+ return siteRoot(world) + '/' + String(url).replace(/^\/+/, '');
68
+ }
69
+
70
+ /** Accept the "leave this page?" question the browser asks once a form was edited. */
71
+ function acceptLeaving(page) {
72
+ if (page.__espocrmDialogs) return;
73
+ page.__espocrmDialogs = true;
74
+ page.on('dialog', (d) => { if (d.type() === 'beforeunload') d.accept().catch(() => {}); });
75
+ }
76
+
77
+ /**
78
+ * Open a route of the site (its pages are routes after a #: `#Case`, `#Case/view/<id>`) and wait for it to settle. The
79
+ * site is one page: a route changes without a page load, so the steps wait for the content they need.
80
+ */
81
+ async function open(world, route) {
82
+ acceptLeaving(world.page);
83
+ const url = /^#/.test(route) ? siteRoot(world) + '/' + route : siteUrl(world, route);
84
+ await gotoUrl(world.page, url);
85
+ await world.page.waitForSelector('body', { state: 'attached', timeout: budget(world) });
86
+ await waitForPageLoad(world.page, (world.minWaitTime && world.minWaitTime.page) || 3000);
87
+ }
88
+
89
+ /** The title of the page on screen. */
90
+ async function pageTitle(world) {
91
+ return tidy(await world.page.title().catch(() => ''));
92
+ }
93
+
94
+ /** The notice the site shows for a moment ("Posted", "Saved"). */
95
+ async function notices(page) {
96
+ return (await page.locator('#notification, #nofitication, .notify .message').allInnerTexts().catch(() => [])).map(tidy).filter(Boolean);
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Users and the session
101
+ // ---------------------------------------------------------------------------
102
+
103
+ /**
104
+ * A user of the `users` registry in cucumber.js: its user name (the site logs in with it), its password and the full
105
+ * name the site shows.
106
+ *
107
+ * @returns {{username: string, password: string, name: string}}
108
+ */
109
+ function resolveUser(world, handle) {
110
+ const users = (world.parameters && world.parameters.users) || {};
111
+ const entry = users[handle];
112
+ if (!entry) {
113
+ throw friendly({
114
+ message: `The account "${handle}" is not in the users registry. Known accounts: ${Object.keys(users).join(', ') || '(none)'}.`,
115
+ hint: `Add it to worldParameters.users in cucumber.js: users: { ${handle}: { username: '${handle}', password: process.env.ESPOCRM_${handle.toUpperCase()}_PASSWORD, name: '...' } }. The account itself is made once by the build of the site, never by a feature.`,
116
+ });
117
+ }
118
+ const password = typeof entry === 'string' ? entry : entry.password;
119
+ if (!password) {
120
+ throw friendly({ message: `The account "${handle}" has no password in the users registry.`, hint: `Set worldParameters.users.${handle}.password in cucumber.js, from an environment variable.` });
121
+ }
122
+ return { username: entry.username || handle, password, name: entry.name || '' };
123
+ }
124
+
125
+ /**
126
+ * Who the browser's session is, asked of the site without moving the page: the full name of the user its session
127
+ * belongs to ('' for a visitor). The site keeps a session in its cookies; its API answers who it is.
128
+ *
129
+ * @returns {Promise<string>}
130
+ */
131
+ async function whoAmI(world) {
132
+ const cookies = await world.context.cookies(siteRoot(world)).catch(() => []);
133
+ if (!cookies.some((c) => c.name === 'auth-token')) return '';
134
+ const r = await world.context.request.get(siteUrl(world, '/api/v1/App/user'), { ignoreHTTPSErrors: true, failOnStatusCode: false }).catch(() => null);
135
+ if (!r || r.status() !== 200) return '';
136
+ const data = await r.json().catch(() => null);
137
+ return tidy(data && data.user && data.user.name);
138
+ }
139
+
140
+ /** Does a session's name stand for an account: its full name, its first name, or its user name. */
141
+ function isAccount(name, user) {
142
+ const n = tidy(name).toLowerCase();
143
+ if (!n) return false;
144
+ const full = tidy(user.name).toLowerCase();
145
+ return n === full || n === user.username.toLowerCase() || (!!full && n.split(' ')[0] === full && full.indexOf(' ') < 0);
146
+ }
147
+
148
+ /**
149
+ * Forget the browser's session: the site's cookies and what it keeps in the browser's storage (a stale entry there
150
+ * would have the login page ask the site who it is, and log its refusal).
151
+ */
152
+ async function dropSession(world) {
153
+ const page = world.page;
154
+ if (page.url().startsWith(siteRoot(world))) {
155
+ await page.evaluate(() => { try { localStorage.clear(); sessionStorage.clear(); } catch (e) { /* none */ } }).catch(() => {});
156
+ }
157
+ if (page.url() !== 'about:blank') await page.goto('about:blank').catch(() => {});
158
+ const host = new URL(siteRoot(world)).hostname;
159
+ const keep = (await world.context.cookies()).filter((c) => c.domain.replace(/^\./, '') !== host);
160
+ await world.context.clearCookies();
161
+ if (keep.length) await world.context.addCookies(keep);
162
+ }
163
+
164
+ /** Fill and submit the login form with a user name and a password. It asserts nothing. */
165
+ async function submitLogin(world, username, password) {
166
+ const page = world.page;
167
+ await open(world, '/');
168
+ await actOrExplain('fill in the login form for', username, async () => {
169
+ await page.locator('#field-userName').waitFor({ state: 'visible', timeout: budget(world) });
170
+ await page.locator('#field-userName').fill(username);
171
+ await page.locator('#field-password').fill(password);
172
+ await page.locator('#btn-login').click();
173
+ }, 'The login form (Username, Password and its "Log in" button) did not show on the front page.');
174
+ await waitForValue(async () => (await page.locator('#nav-menu-dropdown, .alert-danger').count()) > 0, (v) => v, budget(world));
175
+ }
176
+
177
+ /**
178
+ * Log in with an account of the users registry and make sure the session is that account's: through the form, unless
179
+ * the session already is.
180
+ */
181
+ async function signInAs(world, handle) {
182
+ const user = resolveUser(world, handle);
183
+ if (isAccount(await whoAmI(world), user)) {
184
+ if (!world.page.url().startsWith(siteRoot(world))) await open(world, '/');
185
+ return;
186
+ }
187
+ await dropSession(world);
188
+ await submitLogin(world, user.username, user.password);
189
+ const result = await waitForValue(() => whoAmI(world), (name) => isAccount(name, user), budget(world));
190
+ if (!result.ok) {
191
+ const said = tidy(await world.page.locator('.alert-danger').first().innerText({ timeout: 1000 }).catch(() => ''));
192
+ throw friendly({
193
+ message: `Logging in as "${handle}" (user name "${user.username}") did not work${said ? `: the site says "${said}"` : `; the page is ${world.page.url()}`}.`,
194
+ hint: 'Check the user name and the password of this account in worldParameters.users of cucumber.js, and that the account exists on the site and is active.',
195
+ });
196
+ }
197
+ }
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // The site's REST API, as the managing user
201
+ // ---------------------------------------------------------------------------
202
+
203
+ let apiContext = null;
204
+
205
+ /**
206
+ * A call of the site's REST API as the managing user (`worldParameters.manager`), with its own request context: it
207
+ * makes and removes the test content and finds the cases the steps name, and never touches the browser's session.
208
+ */
209
+ async function api(world, method, path, body) {
210
+ const handle = (world.parameters && world.parameters.manager) || 'owner';
211
+ const user = resolveUser(world, handle);
212
+ if (!apiContext) {
213
+ const { request } = require('playwright');
214
+ apiContext = await request.newContext({ ignoreHTTPSErrors: true });
215
+ }
216
+ const r = await apiContext.fetch(siteUrl(world, '/api/v1' + path), {
217
+ method,
218
+ headers: { 'Espo-Authorization': Buffer.from(`${user.username}:${user.password}`).toString('base64'), 'Content-Type': 'application/json' },
219
+ data: body === undefined ? undefined : JSON.stringify(body),
220
+ failOnStatusCode: false,
221
+ });
222
+ const text = await r.text().catch(() => '');
223
+ if (r.status() >= 400) {
224
+ throw friendly({
225
+ message: `The site's API refused ${method} ${path} for the managing user "${handle}" (${r.status()}${r.headers()['x-status-reason'] ? ': ' + r.headers()['x-status-reason'] : ''}).`,
226
+ hint: 'The managing user must be an administrator of the site (worldParameters.manager in cucumber.js), with its password in the users registry.',
227
+ });
228
+ }
229
+ try { return text ? JSON.parse(text) : null; } catch { return text; }
230
+ }
231
+
232
+ /** The end of the managing user's request context. */
233
+ async function disposeApi() {
234
+ if (apiContext) { await apiContext.dispose().catch(() => {}); apiContext = null; }
235
+ }
236
+
237
+ /** The cases of a name (not removed), as the managing user finds them: id, number, name, status. */
238
+ async function findCases(world, name) {
239
+ const q = 'select=id,name,number,status,assignedUserName,teamsNames&maxSize=50'
240
+ + `&where[0][type]=equals&where[0][attribute]=name&where[0][value]=${encodeURIComponent(name)}`;
241
+ const data = await api(world, 'GET', `/Case?${q}`);
242
+ return ((data && data.list) || []).filter((c) => c.name === name);
243
+ }
244
+
245
+ /** The one case of a name, or a friendly error. */
246
+ async function caseNamed(world, name) {
247
+ const found = await findCases(world, name);
248
+ if (!found.length) throw friendly({ message: `There is no case "${name}" the managing user can find.`, hint: 'Make it first with Given there is a case "…", or name a case of the sample content.' });
249
+ return found[0];
250
+ }
251
+
252
+ /** The id of a team by its name. */
253
+ async function teamId(world, name) {
254
+ const data = await api(world, 'GET', `/Team?select=id,name&maxSize=200`);
255
+ const hit = ((data && data.list) || []).find((t) => t.name === name);
256
+ if (!hit) throw friendly({ message: `The site has no team "${name}".`, hint: `Its teams: ${((data && data.list) || []).map((t) => t.name).join(', ') || 'none'}.` });
257
+ return hit.id;
258
+ }
259
+
260
+ /** Remember the name of a case a scenario made, so the After hook removes it. */
261
+ function remember(world, name) {
262
+ world.espocrm = world.espocrm || {};
263
+ world.espocrm.made = world.espocrm.made || new Set();
264
+ world.espocrm.made.add(name);
265
+ }
266
+
267
+ /** Remove the cases of a name, as the managing user. */
268
+ async function removeCases(world, name) {
269
+ for (const c of await findCases(world, name)) await api(world, 'DELETE', `/Case/${c.id}`);
270
+ }
271
+
272
+ // ---------------------------------------------------------------------------
273
+ // The site's fields
274
+ // ---------------------------------------------------------------------------
275
+
276
+ /** Pick a value of a pick list (a field of the record on screen, `.cell[data-name=…]`), as a person does. */
277
+ async function pickOption(world, cell, value) {
278
+ const page = world.page;
279
+ const input = cell.locator('.selectize-control .selectize-input').first();
280
+ await input.waitFor({ state: 'visible', timeout: budget(world) });
281
+ const any = page.locator('.selectize-dropdown .option:visible');
282
+ for (let attempt = 0; attempt < 3 && !(await any.count()); attempt++) {
283
+ await input.click();
284
+ await any.first().waitFor({ state: 'visible', timeout: 3000 }).catch(() => {});
285
+ }
286
+ const option = any.filter({ hasText: exactly(value) }).first();
287
+ if (!(await option.count())) {
288
+ const offered = (await any.allInnerTexts()).map(tidy);
289
+ await page.keyboard.press('Escape');
290
+ throw new Error(`the list offers no "${value}" (${offered.join(', ') || 'nothing'})`);
291
+ }
292
+ await option.click();
293
+ }
294
+
295
+ /** Type into a look-up box and pick the suggestion of that name, as a person does. */
296
+ async function pickSuggestion(world, input, value) {
297
+ const page = world.page;
298
+ await input.fill('');
299
+ await input.type(value, { delay: 40 });
300
+ const suggestion = page.locator('.autocomplete-suggestion:visible').filter({ hasText: exactly(value) }).first();
301
+ const shown = await suggestion.waitFor({ state: 'visible', timeout: budget(world) }).then(() => true).catch(() => false);
302
+ if (!shown) {
303
+ const offered = (await page.locator('.autocomplete-suggestion:visible').allInnerTexts().catch(() => [])).map(tidy);
304
+ throw new Error(`the box offers no "${value}"${offered.length ? ` (it offers ${offered.join(', ')})` : ''}`);
305
+ }
306
+ await suggestion.click();
307
+ }
308
+
309
+ /** Wait until the record on screen has a field (its page is shown), or say what the page is. */
310
+ async function waitForRecord(world) {
311
+ const ok = await world.page.locator('.record .cell[data-name="name"]').first().waitFor({ state: 'visible', timeout: budget(world) * 2 }).then(() => true).catch(() => false);
312
+ if (!ok) {
313
+ const said = tidy(await world.page.locator('body').innerText().catch(() => '')).slice(0, 120);
314
+ throw new Error(`the page shows no case (${said || 'nothing'})`);
315
+ }
316
+ }
317
+
318
+ // ---------------------------------------------------------------------------
319
+ // Console lines a refusal may leave
320
+ // ---------------------------------------------------------------------------
321
+
322
+ /** A mark of the console lines webship-js has collected so far in the scenario. */
323
+ function consoleMark(world) {
324
+ return (world._jsErrors || []).length;
325
+ }
326
+
327
+ /**
328
+ * Let through the console lines a refusal asked for on purpose leaves, and only those: of the lines collected since
329
+ * the mark, the ones each test matches (a test is a function of a line: { type, message, url }). Any other line stays,
330
+ * and fails the scenario as webship-js reports it.
331
+ */
332
+ function allowConsole(world, mark, tests) {
333
+ const list = world._jsErrors;
334
+ if (!Array.isArray(list)) return 0;
335
+ const kept = list.slice(0, mark);
336
+ let allowed = 0;
337
+ for (const line of list.slice(mark)) {
338
+ if (tests.some((t) => t(line))) { allowed += 1; continue; }
339
+ kept.push(line);
340
+ }
341
+ list.length = 0;
342
+ list.push(...kept);
343
+ return allowed;
344
+ }
345
+
346
+ module.exports = {
347
+ budget,
348
+ escapeRegExp,
349
+ exactly,
350
+ tidy,
351
+ actOrExplain,
352
+ waitForValue,
353
+ siteRoot,
354
+ siteUrl,
355
+ acceptLeaving,
356
+ open,
357
+ pageTitle,
358
+ notices,
359
+ resolveUser,
360
+ whoAmI,
361
+ isAccount,
362
+ dropSession,
363
+ submitLogin,
364
+ signInAs,
365
+ api,
366
+ disposeApi,
367
+ findCases,
368
+ caseNamed,
369
+ teamId,
370
+ remember,
371
+ removeCases,
372
+ pickOption,
373
+ pickSuggestion,
374
+ waitForRecord,
375
+ consoleMark,
376
+ allowConsole,
377
+ };
@@ -0,0 +1,118 @@
1
+ 'use strict';
2
+
3
+ // List step definitions: the case list, its filters (all, open, closed) and its search. The list shows the cases the
4
+ // session may see. The site remembers a list's filter and search in the browser: the steps choose them every time.
5
+
6
+ const { When, Then } = require('@cucumber/cucumber');
7
+ const { friendly } = require('webship-js/tests/step-definitions/webship');
8
+ const { budget, tidy, open, waitForValue } = require('./espocrm-helpers');
9
+
10
+ const FILTERS = { all: '', open: 'open', closed: 'closed' };
11
+
12
+ /** The names of the cases the list on screen shows. */
13
+ async function rows(page) {
14
+ return (await page.locator('.list-container table tbody tr.list-row td[data-name="name"]').allInnerTexts().catch(() => [])).map(tidy);
15
+ }
16
+
17
+ /** Do something on the list and wait for the site's answer to the list's request (the cases it shows). */
18
+ async function andTheList(world, action) {
19
+ const page = world.page;
20
+ await Promise.all([
21
+ page.waitForResponse((r) => /\/api\/v1\/Case(?:\?|$)/.test(r.url()) && r.request().method() === 'GET', { timeout: budget(world) * 2 }).catch(() => {}),
22
+ action(),
23
+ ]);
24
+ }
25
+
26
+ /**
27
+ * Open the case list with a filter and a search (none: ''), and wait for its answer. The site remembers the last filter
28
+ * and search: the list's Reset clears them first.
29
+ */
30
+ async function openList(world, filter, words) {
31
+ const page = world.page;
32
+ await open(world, '#Case');
33
+ await page.locator('.search-container .filters-button').first().waitFor({ state: 'visible', timeout: budget(world) * 2 });
34
+ const reset = page.locator('.search-container [data-action="reset"]').first();
35
+ await reset.waitFor({ state: 'visible', timeout: budget(world) }).catch(() => {});
36
+ if (await reset.isVisible().catch(() => false)) await andTheList(world, () => reset.click());
37
+ const box = page.locator('input[data-name="textFilter"]').first();
38
+ if ((await box.inputValue().catch(() => '')) !== '') {
39
+ await box.fill('');
40
+ await andTheList(world, () => box.press('Enter'));
41
+ }
42
+ if (FILTERS[filter]) {
43
+ await page.locator('.search-container .filters-button').first().click();
44
+ await andTheList(world, () => page.locator(`.search-container a[data-action="selectPreset"][data-name="${FILTERS[filter]}"]`).first().click());
45
+ }
46
+ if (words) {
47
+ await box.fill(words);
48
+ await andTheList(world, () => box.press('Enter'));
49
+ }
50
+ await waitForValue(async () => (await page.locator('.list-container').innerText().catch(() => '')).trim().length > 0, (v) => v, budget(world));
51
+ }
52
+
53
+ /**
54
+ * Open the case list with one of its filters: all the cases, the open ones, or the closed ones.
55
+ *
56
+ * Example #1: When I open the open cases
57
+ * Example #2: When I open the closed cases
58
+ * Example #3: And we open all the cases
59
+ * Example #4: Given I open the open cases
60
+ * Example #5: When open all the cases
61
+ *
62
+ */
63
+ When(/^(I |we )*open (all the|the open|the closed) cases$/, async function (pronounCase, which) {
64
+ const filter = which === 'all the' ? 'all' : which.replace(/^the /, '');
65
+ await openList(this, filter, '');
66
+ });
67
+
68
+ /**
69
+ * Search the cases with the case list's search box (all the cases the session may see).
70
+ *
71
+ * Example #1: When I search the cases for "export"
72
+ * Example #2: When I search the cases for "user name"
73
+ * Example #3: And we search the cases for "checklist"
74
+ * Example #4: When I search the cases for "Webship nothing matches this"
75
+ * Example #5: When search the cases for "upload"
76
+ *
77
+ */
78
+ When(/^(I |we )*search the cases for "([^"]*)"$/, async function (pronounCase, words) {
79
+ await openList(this, 'all', words);
80
+ });
81
+
82
+ /**
83
+ * Assert the case list on screen shows a case by its name, or does not.
84
+ *
85
+ * Example #1: Then the case list should show "Exported reports have no date"
86
+ * Example #2: Then the case list should not show "The release checklist of the site"
87
+ * Example #3: And the case list should show "Webship test list"
88
+ * Example #4: But the case list should not show "Attachments larger than 2 MB fail"
89
+ * Example #5: Then the case list should show "The login page does not keep the user name"
90
+ *
91
+ */
92
+ Then(/^the case list should( not)? show "([^"]*)"$/, async function (notCase, name) {
93
+ const result = await waitForValue(() => rows(this.page), (list) => list.includes(name) === !notCase, budget(this));
94
+ if (!result.ok) {
95
+ const names = (result.value || []).map((r) => `"${r}"`);
96
+ throw friendly({
97
+ message: notCase ? `Expected the case list not to show "${name}", but it does.` : `Expected the case list to show "${name}", but it shows ${names.length ? names.join(', ') : 'no case'}.`,
98
+ hint: 'The list shows the cases of the teams the session is in; the open filter leaves out Closed, Rejected and Duplicate, the closed filter shows only those.',
99
+ });
100
+ }
101
+ });
102
+
103
+ /**
104
+ * Assert the case list on screen has no case ("No Data").
105
+ *
106
+ * Example #1: Then the case list should be empty
107
+ * Example #2: And the case list should be empty
108
+ * Example #3: Then the case list should be empty
109
+ * Example #4: But the case list should be empty
110
+ * Example #5: Then the case list should be empty
111
+ *
112
+ */
113
+ Then(/^the case list should be empty$/, async function () {
114
+ const result = await waitForValue(() => rows(this.page), (list) => list.length === 0, budget(this));
115
+ if (!result.ok) throw friendly({ message: `Expected the case list to be empty, but it shows ${result.value.map((r) => `"${r}"`).join(', ')}.`, hint: 'An empty list says "No Data".' });
116
+ const said = tidy(await this.page.locator('.list-container').innerText().catch(() => ''));
117
+ if (!/No Data/i.test(said)) throw friendly({ message: 'The list has no row, but it does not say "No Data".', hint: 'Open the case list or search it first.' });
118
+ });
@@ -0,0 +1,161 @@
1
+ 'use strict';
2
+
3
+ // Session step definitions: logging in with the users registry, the login form and its refusal, logging out, and who
4
+ // the session is.
5
+ //
6
+ // The other step files: espocrm-cases.steps.js (test content, a new case, one case and what a person does on it, what
7
+ // a user may not see or do) and espocrm-lists.steps.js (the case list, its filters and its search).
8
+
9
+ const { Given, When, Then } = require('@cucumber/cucumber');
10
+ const { friendly } = require('webship-js/tests/step-definitions/webship');
11
+ const {
12
+ budget, tidy, open, waitForValue, resolveUser, whoAmI, isAccount, dropSession, submitLogin, signInAs, siteRoot,
13
+ consoleMark, allowConsole,
14
+ } = require('./espocrm-helpers');
15
+
16
+ /**
17
+ * Log in with an account of the users registry in cucumber.js (`worldParameters.users`), by its handle, and make sure
18
+ * the session is that account's: through the login form, unless the session already is.
19
+ *
20
+ * Example #1: Given I am a logged in user with the "developer" user
21
+ * Example #2: Given I am a logged in user with the "owner" user
22
+ * Example #3: Given we are a logged in user with the "sales" user
23
+ * Example #4: And I am a logged in user with the "viewer" user
24
+ * Example #5: When I am a logged in user with the "owner" user
25
+ *
26
+ */
27
+ Given(/^(I am|we are) a logged in user with the "([^"]*)" user$/, async function (pronounCase, handle) {
28
+ await signInAs(this, handle);
29
+ });
30
+
31
+ /**
32
+ * Log in through the form with the user name and the password of an account of the users registry, and assert nothing:
33
+ * the step to use when the scenario is about the login itself.
34
+ *
35
+ * Example #1: When I log in with the "developer" user
36
+ * Example #2: When I log in with the "owner" user
37
+ * Example #3: When we log in with the "sales" user
38
+ * Example #4: And I log in with the "viewer" user
39
+ * Example #5: When log in with the "owner" user
40
+ *
41
+ */
42
+ When(/^(I |we )*log in with the "([^"]*)" user$/, async function (pronounCase, handle) {
43
+ const user = resolveUser(this, handle);
44
+ await dropSession(this);
45
+ await submitLogin(this, user.username, user.password);
46
+ });
47
+
48
+ /**
49
+ * Fill in the login form with a user name and a password as typed in the step, and submit it. It asserts nothing.
50
+ *
51
+ * Example #1: When I log in as "developer" with the password "not-the-right-password"
52
+ * Example #2: When I log in as "nobody" with the password "whatever"
53
+ * Example #3: When we log in as "sales" with the password "wrong"
54
+ * Example #4: And I log in as "owner" with the password "wrong-password"
55
+ * Example #5: When log in as "developer" with the password "x"
56
+ *
57
+ */
58
+ When(/^(I |we )*log in as "([^"]*)" with the password "([^"]*)"$/, async function (pronounCase, username, password) {
59
+ await dropSession(this);
60
+ this.espocrm = Object.assign(this.espocrm || {}, { loginMark: consoleMark(this) });
61
+ await submitLogin(this, username, password);
62
+ });
63
+
64
+ /**
65
+ * Forget the browser's session: a visitor.
66
+ *
67
+ * Example #1: Given I am not logged in
68
+ * Example #2: Given we are not logged in
69
+ * Example #3: And I am not logged in
70
+ * Example #4: When I am not logged in
71
+ * Example #5: Given I am not logged in
72
+ *
73
+ */
74
+ Given(/^(I am|we are) not logged in$/, async function (pronounCase) {
75
+ await dropSession(this);
76
+ });
77
+
78
+ /**
79
+ * Log out through the site (the menu's "Log Out"), and wait until the session is a visitor's.
80
+ *
81
+ * Example #1: When I log out
82
+ * Example #2: When we log out
83
+ * Example #3: And I log out
84
+ * Example #4: Then I log out
85
+ * Example #5: When log out
86
+ *
87
+ */
88
+ When(/^(I |we )*log out$/, async function (pronounCase) {
89
+ if (!(await whoAmI(this))) return;
90
+ if (!this.page.url().startsWith(siteRoot(this))) await open(this, '#');
91
+ await this.page.locator('#nav-menu-dropdown').waitFor({ state: 'visible', timeout: budget(this) });
92
+ await this.page.locator('#nav-menu-dropdown').click();
93
+ await this.page.locator('#navbar a[data-name="logout"]').click();
94
+ await this.page.locator('#field-userName').waitFor({ state: 'visible', timeout: budget(this) }).catch(() => {});
95
+ const result = await waitForValue(() => whoAmI(this), (w) => !w, budget(this));
96
+ if (!result.ok) throw friendly({ message: 'Logged out, but the session is still an account\'s.', hint: 'The menu (the three dots at the top right) has "Log Out".' });
97
+ });
98
+
99
+ /**
100
+ * Assert who the session is: an account's full name, or a handle of the users registry.
101
+ *
102
+ * Example #1: Then I should be logged in as "Developer Test"
103
+ * Example #2: Then I should be logged in as "owner"
104
+ * Example #3: And I should be logged in as "Viewer Test"
105
+ * Example #4: Then we should be logged in as "sales"
106
+ * Example #5: Then should be logged in as "Owner Test"
107
+ *
108
+ */
109
+ Then(/^(I |we )*should be logged in as "([^"]*)"$/, async function (pronounCase, who) {
110
+ const users = (this.parameters && this.parameters.users) || {};
111
+ const user = users[who] ? resolveUser(this, who) : { name: who, username: who };
112
+ const result = await waitForValue(() => whoAmI(this), (name) => isAccount(name, user), budget(this));
113
+ if (!result.ok) {
114
+ throw friendly({
115
+ message: result.value ? `Expected the session to be "${who}", but it is "${result.value}".` : `Expected the session to be "${who}", but nobody is logged in.`,
116
+ hint: 'The menu shows the user\'s full name ("Developer Test").',
117
+ });
118
+ }
119
+ });
120
+
121
+ /**
122
+ * Assert that nobody is logged in.
123
+ *
124
+ * Example #1: Then I should not be logged in
125
+ * Example #2: Then we should not be logged in
126
+ * Example #3: And I should not be logged in
127
+ * Example #4: But I should not be logged in
128
+ * Example #5: Then should not be logged in
129
+ *
130
+ */
131
+ Then(/^(I |we )*should not be logged in$/, async function (pronounCase) {
132
+ const result = await waitForValue(() => whoAmI(this), (w) => !w, budget(this));
133
+ if (!result.ok) throw friendly({ message: `Expected nobody to be logged in, but the session is "${result.value}"'s.`, hint: 'Use Given I am not logged in, or log out first.' });
134
+ });
135
+
136
+ /**
137
+ * Assert that the login just submitted was refused with a message ("Wrong username/password"). The site logs its
138
+ * refusal of the login's request in the browser's console (a 401): this step lets through exactly that line, logged
139
+ * since the login was submitted, and nothing else.
140
+ *
141
+ * Example #1: Then the login should be refused with "Wrong username/password"
142
+ * Example #2: Then the login should be refused with "Wrong"
143
+ * Example #3: And the login should be refused with "Wrong username/password"
144
+ * Example #4: Then the login should be refused with "username/password"
145
+ * Example #5: Then the login should be refused with "Wrong username/password"
146
+ *
147
+ */
148
+ Then(/^the login should be refused with "([^"]*)"$/, async function (text) {
149
+ const read = async () => tidy(await this.page.locator('.alert-danger').allInnerTexts().then((t) => t.join(' ')).catch(() => ''));
150
+ const result = await waitForValue(read, (v) => v.toLowerCase().includes(text.toLowerCase()), budget(this));
151
+ if (!result.ok || (await this.page.locator('#field-userName').count()) === 0) {
152
+ throw friendly({
153
+ message: `Expected the login to be refused with "${text}", but the page does not say so (${result.value ? `it says "${result.value}"` : this.page.url()}).`,
154
+ hint: 'Use it right after "I log in as … with the password …". A login that worked shows no refusal.',
155
+ });
156
+ }
157
+ const mark = (this.espocrm && this.espocrm.loginMark) || 0;
158
+ allowConsole(this, mark, [
159
+ (l) => /^Failed to load resource: the server responded with a status of 401\b/.test(l.message) && /\/api\/v1\/App\/user(?:[?#].*)?$/.test(l.url || ''),
160
+ ]);
161
+ });