playwright-cucumber-ts-steps 0.1.6 → 0.1.7
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.
- package/package.json +1 -1
- package/src/actions/clickSteps.ts +207 -0
- package/src/actions/cookieSteps.ts +29 -0
- package/src/actions/debugSteps.ts +7 -0
- package/src/actions/elementFindSteps.ts +256 -0
- package/src/actions/fillFormSteps.ts +213 -0
- package/src/actions/inputSteps.ts +118 -0
- package/src/actions/interceptionSteps.ts +87 -0
- package/src/actions/miscSteps.ts +414 -0
- package/src/actions/mouseSteps.ts +99 -0
- package/src/actions/scrollSteps.ts +24 -0
- package/src/actions/storageSteps.ts +83 -0
- package/src/assertions/buttonAndTextVisibilitySteps.ts +178 -0
- package/src/assertions/cookieSteps.ts +52 -0
- package/src/assertions/elementSteps.ts +103 -0
- package/src/assertions/formInputSteps.ts +110 -0
- package/src/assertions/interceptionRequestsSteps.ts +216 -0
- package/src/assertions/locationSteps.ts +99 -0
- package/src/assertions/roleTestIdSteps.ts +36 -0
- package/src/assertions/semanticSteps.ts +79 -0
- package/src/assertions/storageSteps.ts +89 -0
- package/src/assertions/visualSteps.ts +98 -0
- package/src/custom_setups/loginHooks.ts +135 -0
- package/src/helpers/checkPeerDeps.ts +19 -0
- package/src/helpers/compareSnapshots.ts +35 -0
- package/src/helpers/hooks.ts +212 -0
- package/src/helpers/utils/fakerUtils.ts +64 -0
- package/src/helpers/utils/index.ts +4 -0
- package/src/helpers/utils/optionsUtils.ts +104 -0
- package/src/helpers/utils/resolveUtils.ts +74 -0
- package/src/helpers/utils/sessionUtils.ts +36 -0
- package/src/helpers/world.ts +93 -0
- package/src/iframes/frames.ts +15 -0
- package/src/index.ts +39 -0
- package/src/register.ts +4 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import {
|
|
4
|
+
Before,
|
|
5
|
+
After,
|
|
6
|
+
BeforeAll,
|
|
7
|
+
AfterAll,
|
|
8
|
+
ITestCaseHookParameter,
|
|
9
|
+
setDefaultTimeout,
|
|
10
|
+
} from "@cucumber/cucumber";
|
|
11
|
+
import * as dotenv from "dotenv";
|
|
12
|
+
import { chromium, devices, Browser, BrowserContextOptions } from "playwright";
|
|
13
|
+
import { compareSnapshots } from "./compareSnapshots";
|
|
14
|
+
import { CustomWorld } from "./world";
|
|
15
|
+
|
|
16
|
+
// Set to 30 seconds
|
|
17
|
+
setDefaultTimeout(30 * 1000);
|
|
18
|
+
dotenv.config();
|
|
19
|
+
|
|
20
|
+
let sharedBrowser: Browser;
|
|
21
|
+
|
|
22
|
+
BeforeAll(async () => {
|
|
23
|
+
sharedBrowser = await chromium.launch({
|
|
24
|
+
headless: process.env.HEADLESS !== "false",
|
|
25
|
+
});
|
|
26
|
+
console.log("🚀 Launched shared browser for all scenarios");
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
AfterAll(async () => {
|
|
30
|
+
await sharedBrowser?.close();
|
|
31
|
+
console.log("🧹 Closed shared browser after all scenarios");
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
Before(async function (this: CustomWorld, scenario: ITestCaseHookParameter) {
|
|
35
|
+
const params = this.parameters || {};
|
|
36
|
+
const ARTIFACT_DIR = params.artifactDir || process.env.TEST_ARTIFACT_DIR || "test-artifacts";
|
|
37
|
+
const SCREENSHOT_DIR = path.resolve(ARTIFACT_DIR, "screenshots");
|
|
38
|
+
const VIDEO_DIR = path.resolve(ARTIFACT_DIR, "videos");
|
|
39
|
+
const TRACE_DIR = path.resolve(ARTIFACT_DIR, "traces");
|
|
40
|
+
const SESSION_FILE = path.resolve(ARTIFACT_DIR, "auth-cookies", "session.json");
|
|
41
|
+
|
|
42
|
+
this.data.artifactDir = ARTIFACT_DIR;
|
|
43
|
+
this.data.screenshotDir = SCREENSHOT_DIR;
|
|
44
|
+
this.data.videoDir = VIDEO_DIR;
|
|
45
|
+
this.data.traceDir = TRACE_DIR;
|
|
46
|
+
this.data.sessionFile = SESSION_FILE;
|
|
47
|
+
|
|
48
|
+
// Modes: "false" | "fail" | "all"
|
|
49
|
+
const traceMode = (params.enableTrace || process.env.ENABLE_TRACE || "false").toLowerCase();
|
|
50
|
+
const screenshotMode = (
|
|
51
|
+
params.enableScreenshots ||
|
|
52
|
+
process.env.ENABLE_SCREENSHOTS ||
|
|
53
|
+
"false"
|
|
54
|
+
).toLowerCase();
|
|
55
|
+
const videoMode = (params.enableVideos || process.env.ENABLE_VIDEOS || "false").toLowerCase();
|
|
56
|
+
|
|
57
|
+
this.data.traceMode = traceMode;
|
|
58
|
+
this.data.screenshotMode = screenshotMode;
|
|
59
|
+
this.data.videoMode = videoMode;
|
|
60
|
+
|
|
61
|
+
const isMobileTag = scenario.pickle.tags.some((t) => t.name === "@mobile");
|
|
62
|
+
const deviceName =
|
|
63
|
+
params.device || process.env.MOBILE_DEVICE || (isMobileTag ? "iPhone 13 Pro" : null);
|
|
64
|
+
const deviceSettings = deviceName ? devices[deviceName] : undefined;
|
|
65
|
+
|
|
66
|
+
if (deviceName && !deviceSettings) {
|
|
67
|
+
throw new Error(`🚫 Invalid MOBILE_DEVICE: "${deviceName}" is not recognized by Playwright.`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const isVisualTest =
|
|
71
|
+
params.enableVisualTest ??
|
|
72
|
+
(process.env.ENABLE_VISUAL_TEST === "true" ||
|
|
73
|
+
scenario.pickle.tags.some((t) => t.name === "@visual"));
|
|
74
|
+
|
|
75
|
+
this.data.enableVisualTest = isVisualTest;
|
|
76
|
+
if (isVisualTest) process.env.VISUAL_TEST = "true";
|
|
77
|
+
|
|
78
|
+
const contextOptions: BrowserContextOptions = {
|
|
79
|
+
...(videoMode !== "false" ? { recordVideo: { dir: VIDEO_DIR } } : {}),
|
|
80
|
+
...(deviceSettings || {}),
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
if (fs.existsSync(SESSION_FILE)) {
|
|
84
|
+
contextOptions.storageState = SESSION_FILE;
|
|
85
|
+
this.log?.("✅ Reusing session from saved file.");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const context = await sharedBrowser.newContext(contextOptions);
|
|
89
|
+
const page = await context.newPage();
|
|
90
|
+
|
|
91
|
+
this.browser = sharedBrowser;
|
|
92
|
+
this.context = context;
|
|
93
|
+
this.page = page;
|
|
94
|
+
|
|
95
|
+
if (traceMode !== "false") {
|
|
96
|
+
await context.tracing.start({
|
|
97
|
+
screenshots: true,
|
|
98
|
+
snapshots: true,
|
|
99
|
+
sources: true,
|
|
100
|
+
});
|
|
101
|
+
this.data.tracingStarted = true;
|
|
102
|
+
this.log?.(`🧪 Tracing started (${traceMode})`);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (deviceName) this.log?.(`📱 Mobile emulation enabled (${deviceName})`);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
After(async function (this: CustomWorld, scenario: ITestCaseHookParameter) {
|
|
109
|
+
const name = scenario.pickle.name.replace(/[^a-z0-9]+/gi, "_").toLowerCase();
|
|
110
|
+
const failed = scenario.result?.status === "FAILED";
|
|
111
|
+
const mode = (value: string | undefined) => value?.toLowerCase();
|
|
112
|
+
|
|
113
|
+
const screenshotMode = mode(this.parameters?.enableScreenshots || process.env.ENABLE_SCREENSHOTS);
|
|
114
|
+
const videoMode = mode(this.parameters?.enableVideos || process.env.ENABLE_VIDEOS);
|
|
115
|
+
const traceMode = mode(this.parameters?.enableTrace || process.env.ENABLE_TRACE);
|
|
116
|
+
|
|
117
|
+
const shouldSaveScreenshot = screenshotMode === "all" || (screenshotMode === "fail" && failed);
|
|
118
|
+
const shouldSaveVideo = videoMode === "all" || (videoMode === "fail" && failed);
|
|
119
|
+
const shouldSaveTrace = traceMode === "all" || (traceMode === "fail" && failed);
|
|
120
|
+
|
|
121
|
+
// 📸 Screenshot
|
|
122
|
+
if (shouldSaveScreenshot && this.page) {
|
|
123
|
+
const screenshotPath = path.join(
|
|
124
|
+
this.data.screenshotDir,
|
|
125
|
+
`${failed ? "failed-" : ""}${name}.png`
|
|
126
|
+
);
|
|
127
|
+
try {
|
|
128
|
+
fs.mkdirSync(this.data.screenshotDir, { recursive: true });
|
|
129
|
+
await this.page.screenshot({ path: screenshotPath, fullPage: true });
|
|
130
|
+
console.log(`🖼️ Screenshot saved: ${screenshotPath}`);
|
|
131
|
+
} catch (err) {
|
|
132
|
+
console.warn("❌ Failed to save screenshot:", err);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// 🎥 Video
|
|
137
|
+
if (this.page && videoMode !== "false") {
|
|
138
|
+
try {
|
|
139
|
+
const video = this.page.video();
|
|
140
|
+
if (video) {
|
|
141
|
+
const rawPath = await video.path();
|
|
142
|
+
if (fs.existsSync(rawPath)) {
|
|
143
|
+
const finalPath = path.join(this.data.videoDir, `${failed ? "failed-" : ""}${name}.webm`);
|
|
144
|
+
fs.mkdirSync(this.data.videoDir, { recursive: true });
|
|
145
|
+
shouldSaveVideo ? fs.renameSync(rawPath, finalPath) : fs.unlinkSync(rawPath);
|
|
146
|
+
console.log(`${shouldSaveVideo ? "🎥 Video saved" : "🧹 Deleted video"}: ${finalPath}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
} catch (err) {
|
|
150
|
+
console.warn(`⚠️ Video error: ${(err as Error).message}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// 🧪 Tracing
|
|
155
|
+
if (this.context && this.data.tracingStarted) {
|
|
156
|
+
const tracePath = path.join(this.data.artifactDir, "traces", `${name}.zip`);
|
|
157
|
+
try {
|
|
158
|
+
fs.mkdirSync(path.dirname(tracePath), { recursive: true });
|
|
159
|
+
await this.context.tracing.stop({ path: tracePath });
|
|
160
|
+
shouldSaveTrace
|
|
161
|
+
? console.log(`📦 Trace saved: ${tracePath}`)
|
|
162
|
+
: (fs.existsSync(tracePath) && fs.unlinkSync(tracePath),
|
|
163
|
+
console.log(`🧹 Trace discarded: ${tracePath}`));
|
|
164
|
+
} catch (err) {
|
|
165
|
+
console.warn("❌ Trace handling error:", err);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 🧪 Visual regression
|
|
170
|
+
if (this.page && this.data.enableVisualTest) {
|
|
171
|
+
const BASELINE_DIR = path.resolve(this.data.artifactDir, "snapshots/baseline");
|
|
172
|
+
const DIFF_DIR = path.resolve(this.data.artifactDir, "snapshots/diff");
|
|
173
|
+
|
|
174
|
+
fs.mkdirSync(BASELINE_DIR, { recursive: true });
|
|
175
|
+
fs.mkdirSync(DIFF_DIR, { recursive: true });
|
|
176
|
+
|
|
177
|
+
const baselinePath = path.join(BASELINE_DIR, `${name}.png`);
|
|
178
|
+
const actualPath = path.join(DIFF_DIR, `${name}.actual.png`);
|
|
179
|
+
const diffPath = path.join(DIFF_DIR, `${name}.diff.png`);
|
|
180
|
+
|
|
181
|
+
await this.page.screenshot({ path: actualPath, fullPage: true });
|
|
182
|
+
|
|
183
|
+
if (!fs.existsSync(baselinePath)) {
|
|
184
|
+
fs.copyFileSync(actualPath, baselinePath);
|
|
185
|
+
console.log(`📸 Created baseline image: ${baselinePath}`);
|
|
186
|
+
} else {
|
|
187
|
+
try {
|
|
188
|
+
const diffPixels = compareSnapshots({
|
|
189
|
+
actualPath,
|
|
190
|
+
baselinePath,
|
|
191
|
+
diffPath,
|
|
192
|
+
threshold: 0.1,
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
console.log(
|
|
196
|
+
diffPixels > 0
|
|
197
|
+
? `⚠️ Visual diff found (${diffPixels} pixels): ${diffPath}`
|
|
198
|
+
: "✅ No visual changes detected"
|
|
199
|
+
);
|
|
200
|
+
} catch (err) {
|
|
201
|
+
console.warn("❌ Snapshot comparison failed:", err);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Cleanup
|
|
207
|
+
try {
|
|
208
|
+
await this.cleanup(scenario);
|
|
209
|
+
} catch (err) {
|
|
210
|
+
this.log?.("❌ Error during cleanup: " + (err as Error).message);
|
|
211
|
+
}
|
|
212
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { faker } from "@faker-js/faker";
|
|
2
|
+
import dayjs from "dayjs";
|
|
3
|
+
|
|
4
|
+
// Supports optional parameters
|
|
5
|
+
type FakerMapping = Record<string, ((param?: string) => string) | (() => string)>;
|
|
6
|
+
|
|
7
|
+
const fakerMapping: FakerMapping = {
|
|
8
|
+
"First Name": () => faker.person.middleName(),
|
|
9
|
+
Name: () => faker.person.middleName(),
|
|
10
|
+
"Last Name": () => faker.person.middleName(),
|
|
11
|
+
Email: () => faker.internet.email(),
|
|
12
|
+
"Phone Number": () => faker.string.numeric(10),
|
|
13
|
+
Number: () => faker.string.numeric(11),
|
|
14
|
+
"Complete Number": () => faker.string.numeric(11),
|
|
15
|
+
"App Colour": () => faker.color.rgb(),
|
|
16
|
+
"App Name": () => faker.commerce.productName(),
|
|
17
|
+
"Role Name": () => faker.person.jobTitle(),
|
|
18
|
+
"Company Name": () => faker.company.name(),
|
|
19
|
+
"Full Name": () => faker.person.fullName(),
|
|
20
|
+
"Disposable Email": () => faker.internet.email({ provider: "inboxkitten.com" }),
|
|
21
|
+
"ALpha Numeric": () => faker.string.numeric(11) + "e",
|
|
22
|
+
"Lorem Word": () => faker.lorem.sentences({ min: 1, max: 3 }),
|
|
23
|
+
Word: () => faker.lorem.word({ length: { min: 5, max: 11 } }),
|
|
24
|
+
"Current Date": () => dayjs().format("YYYY-MM-DD"),
|
|
25
|
+
"Current Date2": () => new Date().toISOString().split("T")[0],
|
|
26
|
+
|
|
27
|
+
MonthsFromNow: (months?: string) => {
|
|
28
|
+
const monthsToAdd = parseInt(months || "0", 10);
|
|
29
|
+
return dayjs().add(monthsToAdd, "month").format("YYYY-MM-DD");
|
|
30
|
+
},
|
|
31
|
+
MonthsAgo: (months?: string) => {
|
|
32
|
+
const monthsToSubtract = parseInt(months || "0", 10);
|
|
33
|
+
return dayjs().subtract(monthsToSubtract, "month").format("YYYY-MM-DD");
|
|
34
|
+
},
|
|
35
|
+
|
|
36
|
+
WeeksFromNow: (weeks?: string) => {
|
|
37
|
+
const weeksToAdd = parseInt(weeks || "0", 10);
|
|
38
|
+
return dayjs().add(weeksToAdd, "week").format("YYYY-MM-DD");
|
|
39
|
+
},
|
|
40
|
+
WeeksAgo: (weeks?: string) => {
|
|
41
|
+
const weeksToSubtract = parseInt(weeks || "0", 10);
|
|
42
|
+
return dayjs().subtract(weeksToSubtract, "week").format("YYYY-MM-DD");
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
DaysFromNow: (days?: string) => {
|
|
46
|
+
const daysToAdd = parseInt(days || "0", 10);
|
|
47
|
+
return dayjs().add(daysToAdd, "day").format("YYYY-MM-DD");
|
|
48
|
+
},
|
|
49
|
+
DaysAgo: (days?: string) => {
|
|
50
|
+
const daysToSubtract = parseInt(days || "0", 10);
|
|
51
|
+
return dayjs().subtract(daysToSubtract, "day").format("YYYY-MM-DD");
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export function evaluateFaker(value: string): string {
|
|
56
|
+
const [key, param] = value.split(":");
|
|
57
|
+
|
|
58
|
+
const fn = fakerMapping[key];
|
|
59
|
+
if (typeof fn === "function") {
|
|
60
|
+
return fn(param);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return value; // fallback to raw value if not mapped
|
|
64
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
//optionsUtils.ts
|
|
2
|
+
import type { DataTable } from "@cucumber/cucumber";
|
|
3
|
+
import type { Locator } from "@playwright/test";
|
|
4
|
+
|
|
5
|
+
type ClickOptions = Parameters<Locator["click"]>[0];
|
|
6
|
+
type DblClickOptions = Parameters<Locator["dblclick"]>[0];
|
|
7
|
+
type HoverOptions = Parameters<Locator["hover"]>[0];
|
|
8
|
+
type FillOptions = Parameters<Locator["fill"]>[1];
|
|
9
|
+
type TypeOptions = Parameters<Locator["type"]>[1];
|
|
10
|
+
type CheckOptions = Parameters<Locator["check"]>[0];
|
|
11
|
+
type UncheckOptions = Parameters<Locator["uncheck"]>[0];
|
|
12
|
+
type SelectOptionOptions = Parameters<Locator["selectOption"]>[1];
|
|
13
|
+
|
|
14
|
+
type KeyboardModifier = NonNullable<NonNullable<ClickOptions>["modifiers"]>[number];
|
|
15
|
+
|
|
16
|
+
export function parseClickOptions(table?: DataTable): Partial<ClickOptions> {
|
|
17
|
+
return parseGenericOptions(table) as Partial<ClickOptions>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function parseDblClickOptions(table?: DataTable): Partial<DblClickOptions> {
|
|
21
|
+
return parseGenericOptions(table) as Partial<DblClickOptions>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function parseHoverOptions(table?: DataTable): Partial<HoverOptions> {
|
|
25
|
+
return parseGenericOptions(table) as Partial<HoverOptions>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function parseTypeOptions(table?: DataTable): Partial<TypeOptions> {
|
|
29
|
+
return parseGenericOptions(table) as unknown as Partial<TypeOptions>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function parseFillOptions(table?: DataTable): Partial<FillOptions> {
|
|
33
|
+
return parseGenericOptions(table) as Partial<FillOptions>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function parseCheckOptions(table?: DataTable): Partial<CheckOptions> {
|
|
37
|
+
return parseGenericOptions(table) as Partial<CheckOptions>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function parseUncheckOptions(table?: DataTable): Partial<UncheckOptions> {
|
|
41
|
+
return parseGenericOptions(table) as Partial<UncheckOptions>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function parseSelectOptions(table?: DataTable): Partial<SelectOptionOptions> {
|
|
45
|
+
return parseGenericOptions(table) as Partial<SelectOptionOptions>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function parseGenericOptions(table?: DataTable): Record<string, any> {
|
|
49
|
+
if (!table) return {};
|
|
50
|
+
|
|
51
|
+
const options: Record<string, any> = {};
|
|
52
|
+
const rows = table.raw();
|
|
53
|
+
|
|
54
|
+
for (const [key, value] of rows) {
|
|
55
|
+
switch (key) {
|
|
56
|
+
case "timeout":
|
|
57
|
+
case "delay":
|
|
58
|
+
case "clickCount":
|
|
59
|
+
options[key] = Number(value);
|
|
60
|
+
break;
|
|
61
|
+
|
|
62
|
+
case "force":
|
|
63
|
+
case "noWaitAfter":
|
|
64
|
+
case "strict":
|
|
65
|
+
case "trial":
|
|
66
|
+
options[key] = value === "true";
|
|
67
|
+
break;
|
|
68
|
+
|
|
69
|
+
case "modifiers":
|
|
70
|
+
options.modifiers = value.split(",").map((v) => v.trim() as KeyboardModifier);
|
|
71
|
+
break;
|
|
72
|
+
|
|
73
|
+
case "button":
|
|
74
|
+
if (["left", "middle", "right"].includes(value)) {
|
|
75
|
+
options.button = value;
|
|
76
|
+
} else {
|
|
77
|
+
throw new Error(`Invalid button option: "${value}"`);
|
|
78
|
+
}
|
|
79
|
+
break;
|
|
80
|
+
|
|
81
|
+
case "position":
|
|
82
|
+
const [x, y] = value.split(",").map((n) => Number(n.trim()));
|
|
83
|
+
if (isNaN(x) || isNaN(y)) {
|
|
84
|
+
throw new Error(`Invalid position format: "${value}"`);
|
|
85
|
+
}
|
|
86
|
+
options.position = { x, y };
|
|
87
|
+
break;
|
|
88
|
+
|
|
89
|
+
default:
|
|
90
|
+
console.warn(`[⚠️ parseGenericOptions] Unknown option "${key}"`);
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return options;
|
|
96
|
+
}
|
|
97
|
+
export function parseExpectOptions(table?: DataTable): { timeout?: number; log?: boolean } {
|
|
98
|
+
if (!table) return {};
|
|
99
|
+
const obj = Object.fromEntries(table.rows());
|
|
100
|
+
return {
|
|
101
|
+
timeout: obj.timeout ? Number(obj.timeout) : undefined,
|
|
102
|
+
log: obj.log === "true",
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// src/helpers/utils/resolveUtils.ts
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { devices } from "@playwright/test";
|
|
5
|
+
import type { CustomWorld } from "../world";
|
|
6
|
+
// Dynamic resolver
|
|
7
|
+
export function resolveValue(input: string): string {
|
|
8
|
+
// Uppercase = environment variable (e.g. TEST_USER)
|
|
9
|
+
if (/^[A-Z0-9_]+$/.test(input)) {
|
|
10
|
+
const envVal = process.env[input];
|
|
11
|
+
if (!envVal) {
|
|
12
|
+
throw new Error(`Environment variable ${input} not found.`);
|
|
13
|
+
}
|
|
14
|
+
return envVal;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Dot = JSON reference (e.g. userData.email)
|
|
18
|
+
if (input.includes(".")) {
|
|
19
|
+
const [fileName, fieldName] = input.split(".");
|
|
20
|
+
const jsonPath = path.resolve("e2e/support/helper/test-data", `${fileName}.json`);
|
|
21
|
+
if (fs.existsSync(jsonPath)) {
|
|
22
|
+
const json = JSON.parse(fs.readFileSync(jsonPath, "utf-8"));
|
|
23
|
+
const value = json[fieldName];
|
|
24
|
+
if (value !== undefined) return value;
|
|
25
|
+
throw new Error(`Field "${fieldName}" not found in ${fileName}.json`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Default to hardcoded value
|
|
30
|
+
return input;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function resolveLoginValue(raw: string, world: CustomWorld): string | undefined {
|
|
34
|
+
// ✅ Alias: @aliasName
|
|
35
|
+
if (raw.startsWith("@")) {
|
|
36
|
+
return world.data[raw.slice(1)];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ✅ JSON: user.json:key
|
|
40
|
+
if (raw.includes(".json:")) {
|
|
41
|
+
const [filename, key] = raw.split(".json:");
|
|
42
|
+
const filePath = path.resolve("test-data", `${filename}.json`);
|
|
43
|
+
if (!fs.existsSync(filePath)) {
|
|
44
|
+
throw new Error(`JSON fixture not found: ${filename}.json`);
|
|
45
|
+
}
|
|
46
|
+
const fileData = JSON.parse(fs.readFileSync(filePath, "utf-8"));
|
|
47
|
+
return fileData[key];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ✅ Fallback to raw value
|
|
51
|
+
return raw;
|
|
52
|
+
}
|
|
53
|
+
// Determine session name from email or username
|
|
54
|
+
export function deriveSessionName(emailOrUser: string, fallback = "default"): string {
|
|
55
|
+
if (!emailOrUser) return `${fallback}User`;
|
|
56
|
+
|
|
57
|
+
const base = emailOrUser.includes("@") ? emailOrUser.split("@")[0] : emailOrUser;
|
|
58
|
+
|
|
59
|
+
return `${base}User`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function resolveSessionPath(world: CustomWorld, name: string) {
|
|
63
|
+
const dir = path.resolve(world.data.artifactDir || "test-artifacts", "auth-cookies");
|
|
64
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
65
|
+
return path.resolve(dir, name.endsWith(".json") ? name : `${name}.json`);
|
|
66
|
+
}
|
|
67
|
+
export function normalizeDeviceName(name: string): string {
|
|
68
|
+
return (
|
|
69
|
+
Object.keys(devices).find(
|
|
70
|
+
(device) =>
|
|
71
|
+
device.toLowerCase().replace(/\s+/g, "") === name.toLowerCase().replace(/[-_\s]+/g, "")
|
|
72
|
+
) || ""
|
|
73
|
+
);
|
|
74
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//sessionUtils.ts
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { BrowserContext } from "playwright";
|
|
5
|
+
|
|
6
|
+
export async function injectStorage(world: any, type: string, key: string, value: string) {
|
|
7
|
+
const page = world.page;
|
|
8
|
+
|
|
9
|
+
if (type === "localStorage") {
|
|
10
|
+
await page.evaluate(([k, v]: [string, string]) => localStorage.setItem(k, v), [key, value]);
|
|
11
|
+
} else if (type === "sessionStorage") {
|
|
12
|
+
await page.evaluate(([k, v]: [string, string]) => sessionStorage.setItem(k, v), [key, value]);
|
|
13
|
+
} else if (type === "cookie") {
|
|
14
|
+
await page.context.addCookies([
|
|
15
|
+
{
|
|
16
|
+
name: key,
|
|
17
|
+
value,
|
|
18
|
+
domain: new URL(page.url()).hostname,
|
|
19
|
+
path: "/",
|
|
20
|
+
httpOnly: false,
|
|
21
|
+
secure: true,
|
|
22
|
+
sameSite: "Lax",
|
|
23
|
+
},
|
|
24
|
+
]);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function saveSessionData(context: BrowserContext, file: string) {
|
|
29
|
+
const storageState = await context.storageState();
|
|
30
|
+
const outDir = "test-artifacts/auth-cookies";
|
|
31
|
+
const outPath = path.resolve(outDir, file);
|
|
32
|
+
|
|
33
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
34
|
+
fs.writeFileSync(outPath, JSON.stringify(storageState, null, 2));
|
|
35
|
+
console.log(`💾 Saved session to ${outPath}`);
|
|
36
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { setWorldConstructor, World, ITestCaseHookParameter } from "@cucumber/cucumber";
|
|
2
|
+
import { Browser, Page, BrowserContext, Locator, FrameLocator, devices } from "@playwright/test";
|
|
3
|
+
import * as dotenv from "dotenv";
|
|
4
|
+
import { chromium } from "playwright";
|
|
5
|
+
|
|
6
|
+
dotenv.config();
|
|
7
|
+
|
|
8
|
+
const isHeadless = process.env.HEADLESS !== "false";
|
|
9
|
+
const slowMo = process.env.SLOWMO ? Number(process.env.SLOWMO) : 0;
|
|
10
|
+
|
|
11
|
+
export interface TestConfig {
|
|
12
|
+
enableScreenshots: boolean;
|
|
13
|
+
enableVisualTest: boolean;
|
|
14
|
+
artifactDir: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class CustomWorld extends World {
|
|
18
|
+
browser!: Browser;
|
|
19
|
+
context!: BrowserContext;
|
|
20
|
+
page!: Page;
|
|
21
|
+
|
|
22
|
+
elements?: Locator;
|
|
23
|
+
element?: Locator;
|
|
24
|
+
frame?: FrameLocator;
|
|
25
|
+
|
|
26
|
+
data: Record<string, any> = {};
|
|
27
|
+
logs: string[] = [];
|
|
28
|
+
testName?: string;
|
|
29
|
+
|
|
30
|
+
config: TestConfig = {
|
|
31
|
+
enableScreenshots: true,
|
|
32
|
+
enableVisualTest: false,
|
|
33
|
+
artifactDir: "test-artifacts",
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
async init(testInfo?: ITestCaseHookParameter) {
|
|
37
|
+
const isMobile = testInfo?.pickle.tags.some((tag) => tag.name === "@mobile");
|
|
38
|
+
const device = isMobile ? devices["Pixel 5"] : undefined;
|
|
39
|
+
|
|
40
|
+
this.browser = await chromium.launch({ headless: isHeadless, slowMo });
|
|
41
|
+
|
|
42
|
+
this.context = await this.browser.newContext({
|
|
43
|
+
...(device || {}),
|
|
44
|
+
recordVideo: { dir: `${this.config.artifactDir}/videos` },
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
this.page = await this.context.newPage();
|
|
48
|
+
this.testName = testInfo?.pickle.name;
|
|
49
|
+
this.log(`🧪 Initialized context${isMobile ? " (mobile)" : ""}`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Returns the current interaction scope: either the main page or active frame.
|
|
54
|
+
*/
|
|
55
|
+
getScope(): Page | FrameLocator {
|
|
56
|
+
return this.frame ?? this.page;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Returns a Locator scoped to the current iframe or page.
|
|
61
|
+
*/
|
|
62
|
+
getLocator(selector: string): Locator {
|
|
63
|
+
return this.getScope().locator(selector);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
exitIframe() {
|
|
67
|
+
this.frame = undefined;
|
|
68
|
+
this.log("⬅️ Exited iframe, scope is now main page");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
log = (message: string) => {
|
|
72
|
+
this.logs.push(message);
|
|
73
|
+
console.log(`[LOG] ${message}`);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
async cleanup(testInfo?: ITestCaseHookParameter) {
|
|
77
|
+
testInfo?.result?.status === "FAILED";
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
await this.page?.close();
|
|
81
|
+
} catch (err) {
|
|
82
|
+
this.log(`⚠️ Error closing page: ${(err as Error).message}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
await this.context?.close();
|
|
87
|
+
} catch (err) {
|
|
88
|
+
this.log(`⚠️ Error closing context: ${(err as Error).message}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
setWorldConstructor(CustomWorld);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { When } from "@cucumber/cucumber";
|
|
2
|
+
// import { expect } from "@playwright/test";
|
|
3
|
+
import type { CustomWorld } from "../helpers/world";
|
|
4
|
+
|
|
5
|
+
When(
|
|
6
|
+
"I find href in iframe {string} and store as {string}",
|
|
7
|
+
async function (this: CustomWorld, iframeSelector: string, key: string) {
|
|
8
|
+
const iframe = this.page.frameLocator(iframeSelector);
|
|
9
|
+
const link = await iframe.locator("a[href]").first();
|
|
10
|
+
const href = await link.getAttribute("href");
|
|
11
|
+
|
|
12
|
+
if (!href) throw new Error("No link found in iframe.");
|
|
13
|
+
this.data[key] = href;
|
|
14
|
+
}
|
|
15
|
+
);
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Actions
|
|
2
|
+
export * from "./actions/clickSteps";
|
|
3
|
+
export * from "./actions/cookieSteps";
|
|
4
|
+
export * from "./actions/debugSteps";
|
|
5
|
+
export * from "./actions/elementFindSteps";
|
|
6
|
+
export * from "./actions/fillFormSteps";
|
|
7
|
+
export * from "./actions/inputSteps";
|
|
8
|
+
export * from "./actions/interceptionSteps";
|
|
9
|
+
export * from "./actions/miscSteps";
|
|
10
|
+
export * from "./actions/mouseSteps";
|
|
11
|
+
export * from "./actions/scrollSteps";
|
|
12
|
+
export * from "./actions/storageSteps";
|
|
13
|
+
|
|
14
|
+
// Assertions
|
|
15
|
+
export * from "./assertions/buttonAndTextVisibilitySteps";
|
|
16
|
+
export * from "./assertions/cookieSteps";
|
|
17
|
+
export * from "./assertions/elementSteps";
|
|
18
|
+
export * from "./assertions/formInputSteps";
|
|
19
|
+
export * from "./assertions/interceptionRequestsSteps";
|
|
20
|
+
export * from "./assertions/locationSteps";
|
|
21
|
+
export * from "./assertions/roleTestIdSteps";
|
|
22
|
+
export * from "./assertions/semanticSteps";
|
|
23
|
+
export * from "./assertions/storageSteps";
|
|
24
|
+
export * from "./assertions/visualSteps";
|
|
25
|
+
|
|
26
|
+
// Iframes
|
|
27
|
+
export * from "./iframes/frames";
|
|
28
|
+
|
|
29
|
+
// Setup (custom hooks, login, etc.)
|
|
30
|
+
export * from "./custom_setups/loginHooks";
|
|
31
|
+
|
|
32
|
+
// Core helpers and utilities
|
|
33
|
+
export * from "./helpers/compareSnapshots";
|
|
34
|
+
export * from "./helpers/hooks";
|
|
35
|
+
export * from "./helpers/utils";
|
|
36
|
+
export * from "./helpers/world";
|
|
37
|
+
|
|
38
|
+
// Types
|
|
39
|
+
export type { CustomWorld } from "./helpers/world";
|
package/src/register.ts
ADDED