webship-js 2.0.0 → 2.0.2

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.
Files changed (34) hide show
  1. package/README.md +1 -7
  2. package/bin/generate-reports.js +191 -0
  3. package/bin/init-webship.js +343 -0
  4. package/bin/postinstall.js +26 -0
  5. package/cucumber.js +59 -1
  6. package/examples/account.html +32 -0
  7. package/examples/diffy/baseline.html +54 -0
  8. package/examples/diffy/changed.html +63 -0
  9. package/examples/diffy/index.html +52 -0
  10. package/examples/index.html +6 -0
  11. package/examples/test--when--i-additionally-select.html +27 -0
  12. package/package.json +11 -4
  13. package/tests/features/diffy/test--diffy-01-example-demo.feature +22 -0
  14. package/tests/features/diffy/test--diffy-02-all-steps.feature +52 -0
  15. package/tests/features/diffy/test--diffy-03-real-api.feature +21 -0
  16. package/tests/features/test--given--i-am-an-anonymous-user.feature +10 -0
  17. package/tests/features/test--then--i-save-screenshot.feature +33 -0
  18. package/tests/features/test--then--i-see-locator.feature +320 -0
  19. package/tests/features/test--then--i-should-see-n-elements.feature +24 -0
  20. package/tests/features/test--then--print-current-url-and-response.feature +21 -0
  21. package/tests/features/test--when--i-additionally-select.feature +30 -0
  22. package/tests/features/test--when--i-follow.feature +22 -0
  23. package/tests/selectors/back-end-selectors.json +13 -0
  24. package/tests/selectors/front-end-selectors.json +16 -0
  25. package/tests/selectors/homepage-selectors.json +13 -0
  26. package/tests/step-definitions/webship-api.js +234 -41
  27. package/tests/step-definitions/webship-screenshot.js +427 -0
  28. package/tests/step-definitions/webship-selectors.js +961 -0
  29. package/tests/step-definitions/webship.js +835 -226
  30. package/tests/step-definitions-diffy/README.md +329 -0
  31. package/tests/step-definitions-diffy/mock-diffy-api/server.js +84 -0
  32. package/tests/step-definitions-diffy/webship-diffy-mock.js +31 -0
  33. package/tests/step-definitions-diffy/webship-diffy.js +472 -0
  34. package/generate-reports.js +0 -22
@@ -0,0 +1,427 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Webship-JS — Screenshot step definitions
5
+ //
6
+ // Saves PNG (and matching .html) screenshots to a configurable directory.
7
+ // Supports manual steps, automatic capture on failed step, and per-step
8
+ // capture for scenarios tagged @screenshots.
9
+ //
10
+ // Configuration: resolved per-scenario with this priority:
11
+ // 1. process.env.WEBSHIP_SCREENSHOT_* (CI / shell — highest)
12
+ // 2. cucumber.js worldParameters.screenshot.* (project-level defaults)
13
+ // 3. built-in defaults
14
+ //
15
+ // Supported env vars / worldParameters keys:
16
+ // WEBSHIP_SCREENSHOT_DIR dir default "./screenshots"
17
+ // WEBSHIP_SCREENSHOT_PURGE purge "true"/"false" — default false
18
+ // WEBSHIP_SCREENSHOT_ON_FAILED onFailed default true
19
+ // WEBSHIP_SCREENSHOT_ON_EVERY_STEP onEveryStep default false
20
+ // WEBSHIP_SCREENSHOT_FULLSCREEN alwaysFullscreen default false
21
+ // WEBSHIP_SCREENSHOT_FAILED_PREFIX failedPrefix default "failed_"
22
+ // WEBSHIP_SCREENSHOT_PATTERN filenamePattern default "{datetime}.{feature_file}.feature_{step_line}.{ext}"
23
+ // WEBSHIP_SCREENSHOT_PATTERN_FAIL filenamePatternFailed default "{failed_prefix}{datetime}.{feature_file}.feature_{step_line}.{ext}"
24
+ // WEBSHIP_SCREENSHOT_INFO_TYPES infoTypes comma list: url,feature,step,datetime
25
+ // ---------------------------------------------------------------------------
26
+
27
+ const { When, Then, Before, After, AfterStep, BeforeAll } = require('@cucumber/cucumber');
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+
31
+ function pick(envVal, paramVal, fallback) {
32
+ if (envVal !== undefined && envVal !== '') return envVal;
33
+ if (paramVal !== undefined && paramVal !== '' && paramVal !== null) return paramVal;
34
+ return fallback;
35
+ }
36
+
37
+ function asBool(v, fallback) {
38
+ if (v === undefined || v === null || v === '') return fallback;
39
+ if (typeof v === 'boolean') return v;
40
+ const s = String(v).toLowerCase();
41
+ return s === '1' || s === 'true' || s === 'yes';
42
+ }
43
+
44
+ function resolveConfig(parameters) {
45
+ const p = (parameters && parameters.screenshot) || {};
46
+ return {
47
+ dir: pick(process.env.WEBSHIP_SCREENSHOT_DIR, p.dir, './screenshots'),
48
+ purge: asBool(pick(process.env.WEBSHIP_SCREENSHOT_PURGE, p.purge, undefined), false),
49
+ onFailed: asBool(pick(process.env.WEBSHIP_SCREENSHOT_ON_FAILED, p.onFailed, undefined), true),
50
+ onEveryStep: asBool(pick(process.env.WEBSHIP_SCREENSHOT_ON_EVERY_STEP, p.onEveryStep, undefined), false),
51
+ alwaysFullscreen: asBool(pick(process.env.WEBSHIP_SCREENSHOT_FULLSCREEN, p.alwaysFullscreen, undefined), false),
52
+ failedPrefix: pick(process.env.WEBSHIP_SCREENSHOT_FAILED_PREFIX, p.failedPrefix, 'failed_'),
53
+ filenamePattern: pick(
54
+ process.env.WEBSHIP_SCREENSHOT_PATTERN,
55
+ p.filenamePattern,
56
+ '{datetime}.{feature_file}.feature_{step_line}.{ext}'
57
+ ),
58
+ filenamePatternFailed: pick(
59
+ process.env.WEBSHIP_SCREENSHOT_PATTERN_FAIL,
60
+ p.filenamePatternFailed,
61
+ '{failed_prefix}{datetime}.{feature_file}.feature_{step_line}.{ext}'
62
+ ),
63
+ infoTypes: String(pick(process.env.WEBSHIP_SCREENSHOT_INFO_TYPES, p.infoTypes, ''))
64
+ .split(',')
65
+ .map(s => s.trim())
66
+ .filter(Boolean),
67
+ };
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Filename tokenizer
72
+ // ---------------------------------------------------------------------------
73
+ function pad(n, w) {
74
+ const s = String(n);
75
+ return s.length >= w ? s : '0'.repeat(w - s.length) + s;
76
+ }
77
+
78
+ function formatDate(d, format) {
79
+ const yyyy = d.getFullYear();
80
+ const MM = pad(d.getMonth() + 1, 2);
81
+ const dd = pad(d.getDate(), 2);
82
+ const HH = pad(d.getHours(), 2);
83
+ const mm = pad(d.getMinutes(), 2);
84
+ const ss = pad(d.getSeconds(), 2);
85
+ if (!format || format === 'Ymd_His') return `${yyyy}${MM}${dd}_${HH}${mm}${ss}`;
86
+ return format
87
+ .replace(/YYYY/g, yyyy)
88
+ .replace(/MM/g, MM)
89
+ .replace(/DD/g, dd)
90
+ .replace(/HH/g, HH)
91
+ .replace(/mm/g, mm)
92
+ .replace(/ss/g, ss);
93
+ }
94
+
95
+ function urlToken(url, qualifier) {
96
+ if (!url) return '';
97
+ let parsed;
98
+ try { parsed = new URL(url); } catch { return url; }
99
+ let out;
100
+ switch (qualifier) {
101
+ case 'origin': out = `${parsed.protocol}//${parsed.host}`; break;
102
+ case 'domain': out = parsed.host; break;
103
+ case 'path': out = parsed.pathname.replace(/^\/+|\/+$/g, ''); break;
104
+ case 'query': out = parsed.search.replace(/^\?/, ''); break;
105
+ case 'fragment': out = parsed.hash.replace(/^#/, ''); break;
106
+ case 'relative':
107
+ out = parsed.pathname.replace(/^\/+|\/+$/g, '') + parsed.search + parsed.hash;
108
+ break;
109
+ default: out = url;
110
+ }
111
+ return out.replace(/[^\w\-]+/g, '_');
112
+ }
113
+
114
+ function replaceTokens(pattern, data) {
115
+ return pattern.replace(/\{([^}]+)\}/g, (match, raw) => {
116
+ const [head, format] = raw.split(':');
117
+ const parts = head.split('_');
118
+ const name = parts.shift();
119
+ const qualifier = parts.join('_') || null;
120
+
121
+ if (name === 'ext') return data.ext || 'html';
122
+ if (name === 'failed' && qualifier === 'prefix') return data.failed_prefix || match;
123
+ if (name === 'feature' && qualifier === 'file') {
124
+ return data.feature_file ? path.basename(data.feature_file, '.feature') : match;
125
+ }
126
+ if (name === 'step') {
127
+ if (qualifier === 'line') {
128
+ const n = Number(data.step_line);
129
+ if (Number.isNaN(n)) return match;
130
+ // sprintf-like: {step_line:%03d}
131
+ if (format && /^%\d*d$/.test(format)) {
132
+ const w = parseInt(format.match(/\d+/)?.[0] || '0', 10);
133
+ return pad(n, w);
134
+ }
135
+ return String(n);
136
+ }
137
+ if (qualifier === 'name' && data.step_name) {
138
+ return String(data.step_name).replace(/[ "]+/g, c => (c === '"' ? '' : '_'));
139
+ }
140
+ return match;
141
+ }
142
+ if (name === 'url') return urlToken(data.url, qualifier);
143
+ if (name === 'datetime') return data.timestamp ? formatDate(new Date(data.timestamp), format) : match;
144
+ return match;
145
+ });
146
+ }
147
+
148
+ // ---------------------------------------------------------------------------
149
+ // State tracked per-scenario
150
+ // ---------------------------------------------------------------------------
151
+ let purgedOnce = false;
152
+
153
+ function ensureDir(dir) {
154
+ fs.mkdirSync(dir, { recursive: true });
155
+ }
156
+
157
+ function purgeDir(dir) {
158
+ if (!fs.existsSync(dir)) return;
159
+ for (const entry of fs.readdirSync(dir)) {
160
+ const full = path.join(dir, entry);
161
+ const stat = fs.lstatSync(full);
162
+ if (stat.isDirectory()) fs.rmSync(full, { recursive: true, force: true });
163
+ else fs.unlinkSync(full);
164
+ }
165
+ }
166
+
167
+ function buildInfo(cfg, ctx) {
168
+ const lines = [];
169
+ for (const type of cfg.infoTypes) {
170
+ if (type === 'url' && ctx.url) lines.push(`Current URL: ${ctx.url}`);
171
+ if (type === 'feature' && ctx.featureTitle) lines.push(`Feature: ${ctx.featureTitle}`);
172
+ if (type === 'step' && ctx.stepText) lines.push(`Step: ${ctx.stepText} (line ${ctx.stepLine || '?'})`);
173
+ if (type === 'datetime') lines.push(`Datetime: ${formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')}`);
174
+ }
175
+ return lines.join('\n');
176
+ }
177
+
178
+ function makeFileName(cfg, ctx, ext, explicitName, isFailed) {
179
+ let pattern;
180
+ if (isFailed) pattern = cfg.filenamePatternFailed;
181
+ else if (explicitName) pattern = explicitName;
182
+ else pattern = cfg.filenamePattern;
183
+
184
+ if (!pattern.endsWith('.{ext}')) pattern += '.{ext}';
185
+
186
+ return replaceTokens(pattern, {
187
+ ext,
188
+ failed_prefix: cfg.failedPrefix,
189
+ feature_file: ctx.featureFile,
190
+ step_line: ctx.stepLine,
191
+ step_name: ctx.stepText,
192
+ timestamp: Date.now(),
193
+ url: ctx.url,
194
+ });
195
+ }
196
+
197
+ async function captureScreenshot(world, options = {}) {
198
+ const cfg = resolveConfig(world.parameters);
199
+ if (!world.page) return;
200
+
201
+ const fullscreen = Boolean(options.fullscreen || cfg.alwaysFullscreen);
202
+ const ctx = world.__screenshotCtx || {};
203
+
204
+ let url = '';
205
+ try { url = world.page.url(); } catch { /* page closed */ }
206
+ ctx.url = url;
207
+
208
+ ensureDir(cfg.dir);
209
+
210
+ // HTML capture (works for all drivers, Playwright content()).
211
+ try {
212
+ let html = await world.page.content();
213
+ const info = buildInfo(cfg, ctx);
214
+ if (info) html = info.replace(/\n/g, '<br/>\n') + '<hr/>\n' + html;
215
+ const htmlName = makeFileName(cfg, ctx, 'html', options.filename, options.isFailed);
216
+ fs.writeFileSync(path.join(cfg.dir, htmlName), html);
217
+ } catch { /* no content yet */ }
218
+
219
+ // PNG capture.
220
+ try {
221
+ const pngName = makeFileName(cfg, ctx, 'png', options.filename, options.isFailed);
222
+ await world.page.screenshot({
223
+ path: path.join(cfg.dir, pngName),
224
+ fullPage: fullscreen,
225
+ });
226
+ } catch { /* driver without screenshot support */ }
227
+ }
228
+
229
+ // ---------------------------------------------------------------------------
230
+ // Hooks
231
+ // ---------------------------------------------------------------------------
232
+ BeforeAll(function () {
233
+ const cfg = resolveConfig(this && this.parameters);
234
+ if (cfg.purge && !purgedOnce) {
235
+ purgeDir(cfg.dir);
236
+ purgedOnce = true;
237
+ }
238
+ });
239
+
240
+ Before(function (scenario) {
241
+ const pickledTags = (scenario.pickle && scenario.pickle.tags) || [];
242
+ this.__screenshotCtx = {
243
+ hasScreenshotsTag: pickledTags.some(t => t.name === '@screenshots'),
244
+ featureFile: (scenario.gherkinDocument && scenario.gherkinDocument.uri) || '',
245
+ featureTitle: (scenario.gherkinDocument && scenario.gherkinDocument.feature && scenario.gherkinDocument.feature.name) || '',
246
+ stepText: '',
247
+ stepLine: 0,
248
+ url: '',
249
+ };
250
+ });
251
+
252
+ AfterStep(async function (step) {
253
+ if (!this.__screenshotCtx) return;
254
+ this.__screenshotCtx.stepText = (step.pickleStep && step.pickleStep.text) || '';
255
+ this.__screenshotCtx.stepLine = step.pickleStep && step.pickleStep.astNodeIds ? 0 : 0;
256
+
257
+ if (step.gherkinDocument && step.pickleStep) {
258
+ const astIds = step.pickleStep.astNodeIds || [];
259
+ const steps = [];
260
+ (step.gherkinDocument.feature.children || []).forEach(child => {
261
+ const container = child.scenario || child.background;
262
+ if (container && container.steps) steps.push(...container.steps);
263
+ });
264
+ const match = steps.find(s => astIds.includes(s.id));
265
+ if (match && match.location) this.__screenshotCtx.stepLine = match.location.line;
266
+ }
267
+
268
+ const cfg = resolveConfig(this.parameters);
269
+ const passed = step.result && step.result.status === 'PASSED';
270
+
271
+ if (!passed && cfg.onFailed) {
272
+ await captureScreenshot(this, { isFailed: true, fullscreen: cfg.alwaysFullscreen });
273
+ return;
274
+ }
275
+ if (passed && (cfg.onEveryStep || this.__screenshotCtx.hasScreenshotsTag)) {
276
+ await captureScreenshot(this, { fullscreen: cfg.alwaysFullscreen });
277
+ }
278
+ });
279
+
280
+ // ---------------------------------------------------------------------------
281
+ // Step definitions
282
+ // ---------------------------------------------------------------------------
283
+
284
+ /**
285
+ * Save a screenshot at the current viewport size.
286
+ *
287
+ * Example #1: Then I save screenshot
288
+ * Example #2: When I save screenshot
289
+ * Example #3: Then save screenshot
290
+ * Example #4: Given I am on "/about-us"
291
+ * Then I save screenshot
292
+ * Example #5: When I go to homepage
293
+ * Then I save screenshot
294
+ * Example #6: Given I am on "/news"
295
+ * When I scroll to "#latest"
296
+ * Then I save screenshot
297
+ * Example #7: Given I am on "/contact"
298
+ * When I fill in "email" with "info@webship.co"
299
+ * Then I save screenshot
300
+ * Example #8: Given I am on "/search?q=UN"
301
+ * Then I save screenshot
302
+ * Example #9: Then I reload page
303
+ * Then I save screenshot
304
+ * Example #10: Given I am on "/partners/un.org"
305
+ * Then I save screenshot
306
+ */
307
+ When(/^(I |we )*save screenshot$/, async function (pronounCase) {
308
+ await captureScreenshot(this, {});
309
+ });
310
+
311
+ /**
312
+ * Save a full-page screenshot (entire scrollable area).
313
+ *
314
+ * Example #1: Then I save fullscreen screenshot
315
+ * Example #2: When I save fullscreen screenshot
316
+ * Example #3: Then save fullscreen screenshot
317
+ * Example #4: Given I am on "/news"
318
+ * Then I save fullscreen screenshot
319
+ * Example #5: Given I am on "/about-us"
320
+ * Then I save fullscreen screenshot
321
+ * Example #6: Given I am on homepage
322
+ * Then I save fullscreen screenshot
323
+ * Example #7: Given I am on "/partners"
324
+ * When I wait 2 seconds
325
+ * Then I save fullscreen screenshot
326
+ * Example #8: Given I am on "/webship"
327
+ * Then I save fullscreen screenshot
328
+ * Example #9: Given I am on "/un.org/reports"
329
+ * Then I save fullscreen screenshot
330
+ * Example #10: Given I am on "/long-article"
331
+ * Then I save fullscreen screenshot
332
+ */
333
+ When(/^(I |we )*save fullscreen screenshot$/, async function (pronounCase) {
334
+ await captureScreenshot(this, { fullscreen: true });
335
+ });
336
+
337
+ /**
338
+ * Resize the viewport to <width> x <height> then save a screenshot.
339
+ *
340
+ * Example #1: Then I save 1440 x 900 screenshot
341
+ * Example #2: Then I save 1200 x 800 screenshot
342
+ * Example #3: Then I save 375 x 667 screenshot
343
+ * Example #4: Then I save 768 x 1024 screenshot
344
+ * Example #5: Then I save 1920 x 1080 screenshot
345
+ * Example #6: Given I am on "/about-us"
346
+ * Then I save 1440 x 900 screenshot
347
+ * Example #7: Given I am on homepage
348
+ * Then I save 375 x 812 screenshot
349
+ * Example #8: Given I am on "/news"
350
+ * Then I save 1024 x 768 screenshot
351
+ * Example #9: Given I am on "/webship.co"
352
+ * Then I save 1366 x 768 screenshot
353
+ * Example #10: Given I am on "/un.org"
354
+ * Then I save 414 x 896 screenshot
355
+ */
356
+ When(/^(I |we )*save (\d+) x (\d+) screenshot$/, async function (pronounCase, width, height) {
357
+ await this.page.setViewportSize({ width: parseInt(width, 10), height: parseInt(height, 10) });
358
+ await captureScreenshot(this, {});
359
+ });
360
+
361
+ /**
362
+ * Resize the viewport to <width> x <height> then save a full-page screenshot.
363
+ *
364
+ * Example #1: Then I save fullscreen 1440 x 900 screenshot
365
+ * Example #2: Then I save fullscreen 1200 x 800 screenshot
366
+ * Example #3: Then I save fullscreen 375 x 667 screenshot
367
+ * Example #4: Then I save fullscreen 768 x 1024 screenshot
368
+ * Example #5: Then I save fullscreen 1920 x 1080 screenshot
369
+ * Example #6: Given I am on "/about-us"
370
+ * Then I save fullscreen 1440 x 900 screenshot
371
+ * Example #7: Given I am on homepage
372
+ * Then I save fullscreen 375 x 812 screenshot
373
+ * Example #8: Given I am on "/webship.co"
374
+ * Then I save fullscreen 1366 x 768 screenshot
375
+ * Example #9: Given I am on "/un.org"
376
+ * Then I save fullscreen 414 x 896 screenshot
377
+ * Example #10: Given I am on "/long-article"
378
+ * Then I save fullscreen 1440 x 900 screenshot
379
+ */
380
+ When(/^(I |we )*save fullscreen (\d+) x (\d+) screenshot$/, async function (pronounCase, width, height) {
381
+ await this.page.setViewportSize({ width: parseInt(width, 10), height: parseInt(height, 10) });
382
+ await captureScreenshot(this, { fullscreen: true });
383
+ });
384
+
385
+ /**
386
+ * Save a screenshot using an explicit filename (tokens supported).
387
+ *
388
+ * Example #1: Then I save screenshot with name "homepage.png"
389
+ * Example #2: Then I save screenshot with name "webship-home"
390
+ * Example #3: Then I save screenshot with name "un-landing-{datetime}.png"
391
+ * Example #4: Then I save screenshot with name "about-us.png"
392
+ * Example #5: Then I save screenshot with name "{feature_file}_{step_line}"
393
+ * Example #6: Then I save screenshot with name "{url_path}.png"
394
+ * Example #7: Given I am on "/news"
395
+ * Then I save screenshot with name "news-latest.png"
396
+ * Example #8: Given I am on "/webship.co"
397
+ * Then I save screenshot with name "webship-index.png"
398
+ * Example #9: Given I am on "/un.org"
399
+ * Then I save screenshot with name "un-home.png"
400
+ * Example #10: Then I save screenshot with name "contact-form-before-submit.png"
401
+ */
402
+ When(/^(I |we )*save screenshot with name "([^"]*)"$/, async function (pronounCase, filename) {
403
+ await captureScreenshot(this, { filename });
404
+ });
405
+
406
+ /**
407
+ * Save a full-page screenshot using an explicit filename (tokens supported).
408
+ *
409
+ * Example #1: Then I save fullscreen screenshot with name "homepage-full.png"
410
+ * Example #2: Then I save fullscreen screenshot with name "webship-home-full"
411
+ * Example #3: Then I save fullscreen screenshot with name "news-{datetime}.png"
412
+ * Example #4: Then I save fullscreen screenshot with name "about-us-full.png"
413
+ * Example #5: Then I save fullscreen screenshot with name "{feature_file}_full.png"
414
+ * Example #6: Then I save fullscreen screenshot with name "{url_path}-full.png"
415
+ * Example #7: Given I am on "/news"
416
+ * Then I save fullscreen screenshot with name "news-full.png"
417
+ * Example #8: Given I am on "/webship.co"
418
+ * Then I save fullscreen screenshot with name "webship-full.png"
419
+ * Example #9: Given I am on "/un.org"
420
+ * Then I save fullscreen screenshot with name "un-home-full.png"
421
+ * Example #10: Then I save fullscreen screenshot with name "long-article-full.png"
422
+ */
423
+ When(/^(I |we )*save fullscreen screenshot with name "([^"]*)"$/, async function (pronounCase, filename) {
424
+ await captureScreenshot(this, { filename, fullscreen: true });
425
+ });
426
+
427
+ module.exports = { resolveConfig, replaceTokens, makeFileName };