@spfx-fast/playwright 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +97 -2
- package/agent/PLAYWRIGHT.md +27 -0
- package/bin/spfx-fast-playwright.mjs +191 -0
- package/examples/sharepoint-smoke.recipe.json +9 -0
- package/package.json +21 -4
- package/src/index.d.ts +33 -0
- package/src/index.js +142 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vilius Vystartas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,98 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @spfx-fast/playwright
|
|
2
2
|
|
|
3
|
-
This
|
|
3
|
+
SPFx-aware Playwright helpers for **any SharePoint Framework project**. This is a development tool: install it in an SPFx project, keep it out of the shipped web-part bundle, and use the signed-in browser state already approved for that test environment. It does not depend on `@spfx-fast/core` or on a particular UI framework.
|
|
4
|
+
|
|
5
|
+
The package builds on Playwright's own test runner, locator model, test recorder, traces, and screenshots. Its added value is a small agent-friendly recipe format, safe same-origin navigation, and a one-command authenticated run that leaves reviewable evidence.
|
|
6
|
+
|
|
7
|
+
## Install in an SPFx project
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install --save-dev @spfx-fast/playwright @playwright/test playwright
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
SPFx is not a Playwright dependency. Nothing from this package is imported by the production web part unless the developer chooses to do so.
|
|
14
|
+
|
|
15
|
+
Scaffold a serial Playwright setup with a starter recipe, generated test spec, agent instructions, screenshots, traces, and an ignored auth-state folder:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx spfx-fast-playwright init
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The generated config uses Playwright storage state only when `SPFX_STORAGE_STATE` is set. Put that file in the ignored `playwright/.auth/` folder or another ignored location; never commit it.
|
|
22
|
+
The scaffold writes `SPFX-PLAYWRIGHT.md` and appends a link to `AGENTS.md` without replacing existing instructions.
|
|
23
|
+
|
|
24
|
+
## Record a test with the Playwright recorder
|
|
25
|
+
|
|
26
|
+
Use a dedicated signed-in test profile. The command calls Playwright Codegen and writes an ordinary Playwright spec:
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
npx spfx-fast-playwright record \
|
|
30
|
+
--url "$SPFX_BASE_URL" \
|
|
31
|
+
--profile-dir "$SPFX_TEST_PROFILE" \
|
|
32
|
+
--out tests/e2e/home-page.spec.ts
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Review generated selectors and assertions. Codegen records actions; it cannot know the business result that should be asserted.
|
|
36
|
+
|
|
37
|
+
## Generate a test mechanically from a small recipe
|
|
38
|
+
|
|
39
|
+
Edit `examples/sharepoint-smoke.recipe.json` for the target site, then:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
npx spfx-fast-playwright validate examples/sharepoint-smoke.recipe.json
|
|
43
|
+
npx spfx-fast-playwright generate examples/sharepoint-smoke.recipe.json --out tests/e2e/sharepoint-smoke.spec.mjs
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The generated file is a normal Playwright Test spec. It can run in a project's standard test runner and uses `SPFX_BASE_URL` plus that project's `storageState` configuration:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
SPFX_BASE_URL="https://tenant.sharepoint.com/sites/your-site" npx playwright test
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
For local state files, keep them out of source control. Playwright authentication state contains session cookies and can impersonate the test user. Prefer a dedicated, least-privilege test account and a dedicated test site.
|
|
53
|
+
|
|
54
|
+
## Run a recipe with a persistent authenticated browser profile
|
|
55
|
+
|
|
56
|
+
This path is useful when a team already has a signed-in Playwright profile and does not want to export its storage state:
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
npx spfx-fast-playwright run examples/sharepoint-smoke.recipe.json \
|
|
60
|
+
--base-url "$SPFX_BASE_URL" \
|
|
61
|
+
--profile-dir "$SPFX_TEST_PROFILE" \
|
|
62
|
+
--artifacts test-results/sharepoint-smoke
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The command runs one browser job, enforces the configured origin, and writes screenshots requested by the recipe, a Playwright trace, and `summary.json`. It never performs a login or reads profile cookies. It does not create or copy a profile. Do not run another job against the same profile at the same time.
|
|
66
|
+
|
|
67
|
+
## Recipe actions
|
|
68
|
+
|
|
69
|
+
Recipes are plain JSON so agents can generate them without writing browser plumbing:
|
|
70
|
+
|
|
71
|
+
| Action | Purpose |
|
|
72
|
+
| --- | --- |
|
|
73
|
+
| `navigate` | Open a path on the configured site origin |
|
|
74
|
+
| `assertPageReady` | Wait for the document body and SharePoint origin |
|
|
75
|
+
| `assertAuthenticated` | Check the current web's SharePoint REST endpoint without reading user data |
|
|
76
|
+
| `click` | Click a semantic role, label, text, test ID, or placeholder locator |
|
|
77
|
+
| `fill` | Fill an accessible input |
|
|
78
|
+
| `select` | Select an option in a native select |
|
|
79
|
+
| `setChecked` | Set a checkbox or radio state |
|
|
80
|
+
| `assertVisible` | Wait for a semantic target to appear |
|
|
81
|
+
| `assertText` | Check exact or contained visible text |
|
|
82
|
+
| `assertValue` | Check an input value |
|
|
83
|
+
| `screenshot` | Save a named PNG to the local artifact directory |
|
|
84
|
+
|
|
85
|
+
Prefer role and label locators over CSS selectors. The recipe format intentionally has no raw JavaScript or arbitrary URL action.
|
|
86
|
+
|
|
87
|
+
## What this does not do
|
|
88
|
+
|
|
89
|
+
- It does not automate Microsoft sign-in, extract tokens, or bypass SharePoint permissions.
|
|
90
|
+
- It does not create or alter SharePoint content. Add explicit steps and user approval before tests that write data.
|
|
91
|
+
- It does not claim a screenshot proves the underlying API or persistence succeeded; assert those separately.
|
|
92
|
+
- It does not replace Playwright Codegen. Use Codegen for interactive recording, then add meaningful assertions.
|
|
93
|
+
|
|
94
|
+
Screenshots and traces may contain tenant content. Keep `test-results/`, `playwright-report/`, authentication files, and profile directories local; review artifacts before sharing.
|
|
95
|
+
|
|
96
|
+
## Package status
|
|
97
|
+
|
|
98
|
+
This is the early `0.1.0` companion package. It is framework-agnostic across SPFx projects and ships independently from `@spfx-fast/core`.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# SPFx Playwright instructions
|
|
2
|
+
|
|
3
|
+
Use this guide for tests against any SharePoint Framework project. The package is a development tool and does not require `@spfx-fast/core`.
|
|
4
|
+
|
|
5
|
+
## Start with the existing project
|
|
6
|
+
|
|
7
|
+
- Use its installed Playwright version, configuration, signed-in test account, and test site.
|
|
8
|
+
- Set `SPFX_BASE_URL` to the SharePoint **web URL**. Set `SPFX_STORAGE_STATE` only to a local ignored file when that project already uses saved state.
|
|
9
|
+
- Never automate sign-in, read or print cookies, copy the user's daily browser profile, or commit authentication state.
|
|
10
|
+
- Keep a persistent profile to one browser job at a time.
|
|
11
|
+
|
|
12
|
+
## Generate and run
|
|
13
|
+
|
|
14
|
+
- For an interactive recording, use `spfx-fast-playwright record` with the project's dedicated signed-in profile. Review generated selectors and add assertions for the expected user-visible result.
|
|
15
|
+
- For a small repeatable workflow, write or adjust a JSON recipe, run `spfx-fast-playwright validate`, then `generate` or `run` it.
|
|
16
|
+
- Prefer role and label locators. Add explicit waits for the condition under test; do not use `networkidle` as a generic SharePoint readiness signal.
|
|
17
|
+
- Use `assertAuthenticated` to check the current web's REST response without reading account details.
|
|
18
|
+
- Keep navigation within the configured origin. A sign-in redirect is a failed precondition, not a passing page load.
|
|
19
|
+
- Use the real QA page and data needed for the result. A zero-to-zero comparison or a page missing the web part is inconclusive.
|
|
20
|
+
|
|
21
|
+
## Prove and report
|
|
22
|
+
|
|
23
|
+
- Default to read-only checks. For tests that write SharePoint data, use dedicated test records and an explicit cleanup plan; do not alter production content.
|
|
24
|
+
- Inspect the generated spec before running it. Then inspect `summary.json`, each screenshot, and the trace after a run.
|
|
25
|
+
- A screenshot proves only what was visible. Add request or persisted-state assertions when the behavior depends on SharePoint REST, Graph, save, or publish.
|
|
26
|
+
- If a control cannot be reached after three attempts, stop and report the blocker with its screenshot/trace. Do not loop or mark an inconclusive run as passed.
|
|
27
|
+
- Do not share traces or screenshots until checking for tenant content and personal data.
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { access, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, resolve } from "node:path";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
import { generateTestSource, runRecipe, validateBaseUrl, validateRecipe } from "../src/index.js";
|
|
9
|
+
|
|
10
|
+
const help = `SPFx Fast Playwright\n\nCommands:\n init [--force] Scaffold config and a smoke recipe\n validate <recipe.json> Validate a recipe\n generate <recipe.json> --out <test.spec.mjs> Generate a native Playwright test\n run <recipe.json> --base-url <url> --profile-dir <dir> [--artifacts <dir>] [--headless]\n record --url <url> --profile-dir <dir> --out <test.spec.ts> Start Playwright Codegen\n`;
|
|
11
|
+
|
|
12
|
+
const parsed = parseArgs({
|
|
13
|
+
args: process.argv.slice(2),
|
|
14
|
+
allowPositionals: true,
|
|
15
|
+
strict: true,
|
|
16
|
+
options: {
|
|
17
|
+
out: { type: "string" },
|
|
18
|
+
"base-url": { type: "string" },
|
|
19
|
+
"profile-dir": { type: "string" },
|
|
20
|
+
artifacts: { type: "string" },
|
|
21
|
+
"timeout-ms": { type: "string" },
|
|
22
|
+
url: { type: "string" },
|
|
23
|
+
headless: { type: "boolean", default: false },
|
|
24
|
+
force: { type: "boolean", default: false },
|
|
25
|
+
help: { type: "boolean", short: "h", default: false },
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const [command, recipeFile] = parsed.positionals;
|
|
30
|
+
const options = parsed.values;
|
|
31
|
+
|
|
32
|
+
async function readRecipe(file) {
|
|
33
|
+
if (!file) throw new Error("Supply a recipe JSON file.");
|
|
34
|
+
try { return validateRecipe(JSON.parse(await readFile(resolve(file), "utf8"))); }
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error instanceof TypeError) throw error;
|
|
37
|
+
throw new Error("Could not read a valid recipe JSON file.");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function outputPath(file) {
|
|
42
|
+
if (!file) throw new Error("Supply --out.");
|
|
43
|
+
const target = resolve(file);
|
|
44
|
+
if (!options.force) {
|
|
45
|
+
try { await access(target); throw new Error("Output already exists; pass --force to replace it."); }
|
|
46
|
+
catch (error) { if (error.message.includes("already exists")) throw error; }
|
|
47
|
+
}
|
|
48
|
+
await mkdir(dirname(target), { recursive: true });
|
|
49
|
+
return target;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function requireProfileDirectory(value) {
|
|
53
|
+
if (!value) throw new Error("Supply an existing --profile-dir. The command will not create or copy a signed-in profile.");
|
|
54
|
+
const path = resolve(value);
|
|
55
|
+
let metadata;
|
|
56
|
+
try { metadata = await stat(path); } catch { throw new Error("The supplied profile directory does not exist."); }
|
|
57
|
+
if (!metadata.isDirectory()) throw new Error("The supplied profile path must be a directory.");
|
|
58
|
+
return path;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function main() {
|
|
62
|
+
if (options.help || !command || command === "help") {
|
|
63
|
+
console.log(help);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (command === "init") {
|
|
67
|
+
const agentGuide = await readFile(new URL("../agent/PLAYWRIGHT.md", import.meta.url), "utf8");
|
|
68
|
+
const smokeRecipe = {
|
|
69
|
+
name: "SharePoint page is available to the signed-in user",
|
|
70
|
+
steps: [
|
|
71
|
+
{ action: "navigate", path: "/sites/your-site" },
|
|
72
|
+
{ action: "assertPageReady" },
|
|
73
|
+
{ action: "assertAuthenticated" },
|
|
74
|
+
{ action: "screenshot", name: "sharepoint-page", fullPage: true },
|
|
75
|
+
],
|
|
76
|
+
};
|
|
77
|
+
const files = [
|
|
78
|
+
["playwright.config.ts", `import { defineConfig } from "@playwright/test";\n\nexport default defineConfig({\n testDir: "./tests/e2e",\n fullyParallel: false,\n workers: 1,\n reporter: [["list"], ["html", { open: "never" }]],\n use: {\n baseURL: process.env.SPFX_BASE_URL,\n storageState: process.env.SPFX_STORAGE_STATE || undefined,\n actionTimeout: 15_000,\n navigationTimeout: 45_000,\n screenshot: "only-on-failure",\n trace: "retain-on-failure",\n viewport: { width: 1440, height: 900 },\n },\n});\n`],
|
|
79
|
+
["tests/e2e/sharepoint-smoke.recipe.json", `${JSON.stringify(smokeRecipe, null, 2)}\n`],
|
|
80
|
+
["tests/e2e/sharepoint-smoke.spec.mjs", generateTestSource(smokeRecipe)],
|
|
81
|
+
["playwright/.auth/.gitignore", "*\n!.gitignore\n"],
|
|
82
|
+
["SPFX-PLAYWRIGHT.md", agentGuide],
|
|
83
|
+
];
|
|
84
|
+
if (!options.force) {
|
|
85
|
+
for (const [file] of files) {
|
|
86
|
+
try { await access(resolve(file)); throw new Error(`Refusing to overwrite ${file}; pass --force to replace generated files.`); }
|
|
87
|
+
catch (error) { if (error.message.startsWith("Refusing")) throw error; }
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
for (const [file, contents] of files) {
|
|
91
|
+
const target = resolve(file);
|
|
92
|
+
await mkdir(dirname(target), { recursive: true });
|
|
93
|
+
await writeFile(target, contents, "utf8");
|
|
94
|
+
}
|
|
95
|
+
const agentsFile = resolve("AGENTS.md");
|
|
96
|
+
let existingAgents = "";
|
|
97
|
+
try { existingAgents = await readFile(agentsFile, "utf8"); }
|
|
98
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
99
|
+
const marker = "<!-- spfx-fast-playwright:agent-instructions -->";
|
|
100
|
+
if (!existingAgents.includes(marker)) {
|
|
101
|
+
const link = `${marker}\n## SharePoint end-to-end tests\nRead [SPFX-PLAYWRIGHT.md](SPFX-PLAYWRIGHT.md) when creating or running authenticated SharePoint browser tests.\n`;
|
|
102
|
+
const prefix = existingAgents ? `${existingAgents}${existingAgents.endsWith("\n") ? "" : "\n"}\n` : "# Agent instructions\n\n";
|
|
103
|
+
await writeFile(agentsFile, `${prefix}${link}`, "utf8");
|
|
104
|
+
}
|
|
105
|
+
console.log("Created Playwright config, a generated smoke test, agent instructions, and an ignored auth-state folder.");
|
|
106
|
+
console.log("Set SPFX_BASE_URL to the SharePoint web URL. Keep SPFX_STORAGE_STATE private.");
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (command === "validate") {
|
|
110
|
+
const recipe = await readRecipe(recipeFile);
|
|
111
|
+
console.log(`Recipe valid: ${recipe.name} (${recipe.steps.length} steps).`);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (command === "generate") {
|
|
115
|
+
const recipe = await readRecipe(recipeFile);
|
|
116
|
+
const target = await outputPath(options.out);
|
|
117
|
+
if (!/\.spec\.(?:mjs|ts)$/.test(target)) throw new Error("Generated tests must end in .spec.mjs or .spec.ts.");
|
|
118
|
+
await writeFile(target, generateTestSource(recipe), "utf8");
|
|
119
|
+
console.log(`Generated native Playwright test: ${target}`);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (command === "record") {
|
|
123
|
+
const profile = await requireProfileDirectory(options["profile-dir"]);
|
|
124
|
+
const output = await outputPath(options.out);
|
|
125
|
+
if (!/\.spec\.(?:mjs|ts)$/.test(output)) throw new Error("Recorded tests must end in .spec.mjs or .spec.ts.");
|
|
126
|
+
const url = validateBaseUrl(options.url).href;
|
|
127
|
+
const requireFromProject = createRequire(pathToFileURL(resolve("package.json")));
|
|
128
|
+
const playwrightEntry = requireFromProject.resolve("playwright");
|
|
129
|
+
const cli = resolve(dirname(playwrightEntry), "cli.js");
|
|
130
|
+
const result = spawnSync(process.execPath, [cli, "codegen", `--user-data-dir=${profile}`, `--output=${output}`, "--viewport-size=1440,900", url], { stdio: "inherit" });
|
|
131
|
+
if (result.error) throw new Error("Playwright Codegen could not start. Check that Playwright is installed in this project.");
|
|
132
|
+
if (result.status !== 0) process.exitCode = result.status ?? 1;
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (command === "run") {
|
|
136
|
+
const recipe = await readRecipe(recipeFile);
|
|
137
|
+
const base = validateBaseUrl(options["base-url"]);
|
|
138
|
+
const profile = await requireProfileDirectory(options["profile-dir"]);
|
|
139
|
+
const artifactRoot = resolve(options.artifacts ?? "test-results/spfx-fast-playwright");
|
|
140
|
+
const timeoutMs = Number(options["timeout-ms"] ?? 15000);
|
|
141
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1) throw new Error("--timeout-ms must be a positive integer.");
|
|
142
|
+
await mkdir(artifactRoot, { recursive: true });
|
|
143
|
+
let artifacts = artifactRoot;
|
|
144
|
+
try {
|
|
145
|
+
if ((await readdir(artifactRoot)).length > 0) {
|
|
146
|
+
artifacts = resolve(artifactRoot, `run-${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`);
|
|
147
|
+
}
|
|
148
|
+
} catch {}
|
|
149
|
+
await mkdir(artifacts, { recursive: true });
|
|
150
|
+
const { chromium } = await import("playwright");
|
|
151
|
+
const context = await chromium.launchPersistentContext(profile, {
|
|
152
|
+
headless: options.headless,
|
|
153
|
+
viewport: { width: 1440, height: 900 },
|
|
154
|
+
});
|
|
155
|
+
let page;
|
|
156
|
+
let result;
|
|
157
|
+
let error;
|
|
158
|
+
try {
|
|
159
|
+
page = context.pages()[0] ?? await context.newPage();
|
|
160
|
+
await context.tracing.start({ screenshots: true, snapshots: true, sources: false });
|
|
161
|
+
result = await runRecipe(page, recipe, { baseUrl: base.href, screenshotDir: artifacts, timeoutMs });
|
|
162
|
+
} catch (cause) {
|
|
163
|
+
error = cause;
|
|
164
|
+
if (page) {
|
|
165
|
+
try { await page.screenshot({ path: resolve(artifacts, "failure.png"), fullPage: true }); } catch {}
|
|
166
|
+
}
|
|
167
|
+
} finally {
|
|
168
|
+
try { await context.tracing.stop({ path: resolve(artifacts, "trace.zip") }); } catch {}
|
|
169
|
+
await context.close();
|
|
170
|
+
}
|
|
171
|
+
const report = {
|
|
172
|
+
name: recipe.name,
|
|
173
|
+
status: error ? "failed" : "passed",
|
|
174
|
+
stepCount: recipe.steps.length,
|
|
175
|
+
screenshots: error ? ["failure.png"] : result.screenshots.map((file) => file.slice(artifacts.length + 1)),
|
|
176
|
+
trace: "trace.zip",
|
|
177
|
+
failedStep: error?.step ?? null,
|
|
178
|
+
error: error ? error.message : null,
|
|
179
|
+
};
|
|
180
|
+
await writeFile(resolve(artifacts, "summary.json"), `${JSON.stringify(report, null, 2)}\n`);
|
|
181
|
+
console.log(JSON.stringify({ ...report, artifactDirectory: artifacts }, null, 2));
|
|
182
|
+
if (error) process.exitCode = 1;
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
throw new Error(`Unknown command: ${command}. Use --help.`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
main().catch((error) => {
|
|
189
|
+
console.error(error instanceof Error ? error.message : "Command failed.");
|
|
190
|
+
process.exitCode = 1;
|
|
191
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "SharePoint page is available to the signed-in user",
|
|
3
|
+
"steps": [
|
|
4
|
+
{ "action": "navigate", "path": "/sites/your-site" },
|
|
5
|
+
{ "action": "assertPageReady" },
|
|
6
|
+
{ "action": "assertAuthenticated" },
|
|
7
|
+
{ "action": "screenshot", "name": "sharepoint-page", "fullPage": true }
|
|
8
|
+
]
|
|
9
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spfx-fast/playwright",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"author": "Vilius Vystartas",
|
|
5
|
+
"description": "Authenticated, recipe-driven Playwright testing helpers for any SharePoint Framework project.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://github.com/vystartasv/spfx-fast#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/vystartasv/spfx-fast.git",
|
|
11
|
+
"directory": "packages/playwright"
|
|
12
|
+
},
|
|
13
|
+
"bugs": { "url": "https://github.com/vystartasv/spfx-fast/issues" },
|
|
14
|
+
"type": "module",
|
|
15
|
+
"engines": { "node": ">=18" },
|
|
16
|
+
"main": "./src/index.js",
|
|
17
|
+
"types": "./src/index.d.ts",
|
|
18
|
+
"exports": { ".": { "types": "./src/index.d.ts", "import": "./src/index.js" } },
|
|
19
|
+
"bin": { "spfx-fast-playwright": "./bin/spfx-fast-playwright.mjs" },
|
|
20
|
+
"files": ["src", "bin", "README.md", "LICENSE", "examples", "agent"],
|
|
21
|
+
"peerDependencies": { "@playwright/test": ">=1.50.0 <2", "playwright": ">=1.50.0 <2" },
|
|
22
|
+
"keywords": ["spfx", "sharepoint", "playwright", "e2e", "testing", "agents"]
|
|
23
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Page } from "playwright";
|
|
2
|
+
|
|
3
|
+
export type RecipeLocator =
|
|
4
|
+
| { role: string; name: string; exact?: boolean }
|
|
5
|
+
| { text: string; exact?: boolean }
|
|
6
|
+
| { label: string; exact?: boolean }
|
|
7
|
+
| { testId: string }
|
|
8
|
+
| { placeholder: string; exact?: boolean };
|
|
9
|
+
|
|
10
|
+
export type RecipeStep =
|
|
11
|
+
| { action: "navigate"; path: string }
|
|
12
|
+
| { action: "assertPageReady" }
|
|
13
|
+
| { action: "assertAuthenticated" }
|
|
14
|
+
| { action: "click" | "assertVisible"; locator: RecipeLocator }
|
|
15
|
+
| { action: "fill"; locator: RecipeLocator; value: string }
|
|
16
|
+
| { action: "select"; locator: RecipeLocator; value: string }
|
|
17
|
+
| { action: "setChecked"; locator: RecipeLocator; checked: boolean }
|
|
18
|
+
| { action: "assertText" | "assertValue"; locator: RecipeLocator; expected: string; exact?: boolean }
|
|
19
|
+
| { action: "screenshot"; name: string; fullPage?: boolean };
|
|
20
|
+
|
|
21
|
+
export interface SharePointRecipe {
|
|
22
|
+
name: string;
|
|
23
|
+
steps: RecipeStep[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function validateRecipe(recipe: unknown): SharePointRecipe;
|
|
27
|
+
export function validateBaseUrl(baseUrl: string): URL;
|
|
28
|
+
export function runRecipe(page: Page, recipe: SharePointRecipe, options: {
|
|
29
|
+
baseUrl: string;
|
|
30
|
+
screenshotDir?: string;
|
|
31
|
+
timeoutMs?: number;
|
|
32
|
+
}): Promise<{ name: string; steps: number; screenshots: string[] }>;
|
|
33
|
+
export function generateTestSource(recipe: SharePointRecipe): string;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
const actions = new Set(["navigate", "assertPageReady", "assertAuthenticated", "click", "fill", "select", "setChecked", "assertVisible", "assertText", "assertValue", "screenshot"]);
|
|
5
|
+
const locatorKeys = new Set(["role", "text", "label", "testId", "placeholder"]);
|
|
6
|
+
|
|
7
|
+
export function validateRecipe(recipe) {
|
|
8
|
+
if (!recipe || typeof recipe !== "object" || Array.isArray(recipe)) throw new TypeError("Recipe must be a JSON object.");
|
|
9
|
+
if (typeof recipe.name !== "string" || !recipe.name.trim()) throw new TypeError("Recipe needs a non-empty name.");
|
|
10
|
+
if (!Array.isArray(recipe.steps) || recipe.steps.length === 0) throw new TypeError("Recipe needs at least one step.");
|
|
11
|
+
|
|
12
|
+
for (const [index, step] of recipe.steps.entries()) {
|
|
13
|
+
if (!step || typeof step !== "object" || Array.isArray(step) || !actions.has(step.action)) {
|
|
14
|
+
throw new TypeError(`Recipe step ${index + 1} has an unsupported action.`);
|
|
15
|
+
}
|
|
16
|
+
if (step.action === "navigate" && (typeof step.path !== "string" || !step.path.startsWith("/") || step.path.startsWith("//") || /[?#]/.test(step.path))) {
|
|
17
|
+
throw new TypeError(`Recipe step ${index + 1} needs a same-site path beginning with / and no query or fragment.`);
|
|
18
|
+
}
|
|
19
|
+
if (["click", "fill", "select", "setChecked", "assertVisible", "assertText", "assertValue"].includes(step.action)) validateLocator(step.locator, index + 1);
|
|
20
|
+
if (["fill", "select"].includes(step.action) && typeof step.value !== "string") throw new TypeError(`Recipe step ${index + 1} needs a string value.`);
|
|
21
|
+
if (step.action === "setChecked" && typeof step.checked !== "boolean") throw new TypeError(`Recipe step ${index + 1} needs a boolean checked value.`);
|
|
22
|
+
if (["assertText", "assertValue"].includes(step.action) && typeof step.expected !== "string") throw new TypeError(`Recipe step ${index + 1} needs expected text.`);
|
|
23
|
+
if (step.action === "screenshot" && (typeof step.name !== "string" || !/^[\w-]+$/.test(step.name))) {
|
|
24
|
+
throw new TypeError(`Recipe step ${index + 1} needs a screenshot name using only letters, numbers, _ or -.`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return recipe;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function validateLocator(locator, stepNumber) {
|
|
31
|
+
if (!locator || typeof locator !== "object" || Array.isArray(locator)) throw new TypeError(`Recipe step ${stepNumber} needs a locator.`);
|
|
32
|
+
const keys = Object.keys(locator).filter((key) => locatorKeys.has(key));
|
|
33
|
+
if (keys.length !== 1 || typeof locator[keys[0]] !== "string" || !locator[keys[0]].trim()) {
|
|
34
|
+
throw new TypeError(`Recipe step ${stepNumber} needs exactly one non-empty role, text, label, testId or placeholder locator.`);
|
|
35
|
+
}
|
|
36
|
+
if (keys[0] === "role" && (typeof locator.name !== "string" || !locator.name.trim())) {
|
|
37
|
+
throw new TypeError(`Recipe step ${stepNumber} role locator needs an accessible name.`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function validateBaseUrl(baseUrl) {
|
|
42
|
+
let url;
|
|
43
|
+
try { url = new URL(baseUrl); } catch { throw new TypeError("Provide a valid SPFX_BASE_URL."); }
|
|
44
|
+
const secure = url.protocol === "https:" || (url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname));
|
|
45
|
+
if (!secure) throw new TypeError("SPFX_BASE_URL must use HTTPS (HTTP is allowed only for localhost).");
|
|
46
|
+
if (url.username || url.password || url.search || url.hash) throw new TypeError("SPFX_BASE_URL must not contain credentials, query values or a fragment.");
|
|
47
|
+
return url;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function locatorFor(page, locator) {
|
|
51
|
+
if (locator.role) return page.getByRole(locator.role, { name: locator.name, exact: locator.exact ?? true });
|
|
52
|
+
if (locator.text) return page.getByText(locator.text, { exact: locator.exact ?? true });
|
|
53
|
+
if (locator.label) return page.getByLabel(locator.label, { exact: locator.exact ?? true });
|
|
54
|
+
if (locator.testId) return page.getByTestId(locator.testId);
|
|
55
|
+
return page.getByPlaceholder(locator.placeholder, { exact: locator.exact ?? true });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function assertSameOrigin(page, base) {
|
|
59
|
+
const current = new URL(page.url());
|
|
60
|
+
if (current.origin !== base.origin) throw new Error("Navigation left the configured SharePoint origin; check sign-in state and page links.");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function runRecipe(page, recipe, { baseUrl, screenshotDir, timeoutMs = 15000 } = {}) {
|
|
64
|
+
validateRecipe(recipe);
|
|
65
|
+
const base = validateBaseUrl(baseUrl);
|
|
66
|
+
const screenshots = [];
|
|
67
|
+
if (screenshotDir) await mkdir(screenshotDir, { recursive: true });
|
|
68
|
+
|
|
69
|
+
for (const [index, step] of recipe.steps.entries()) {
|
|
70
|
+
try {
|
|
71
|
+
if (step.action === "navigate") {
|
|
72
|
+
const destination = new URL(step.path, base);
|
|
73
|
+
if (destination.origin !== base.origin) throw new Error("Navigation must stay on the configured SharePoint origin.");
|
|
74
|
+
const response = await page.goto(destination.href, { waitUntil: "domcontentloaded", timeout: timeoutMs });
|
|
75
|
+
if (response && response.status() >= 400) throw new Error(`Page returned HTTP ${response.status()}.`);
|
|
76
|
+
assertSameOrigin(page, base);
|
|
77
|
+
} else if (step.action === "assertPageReady") {
|
|
78
|
+
await page.waitForLoadState("domcontentloaded", { timeout: timeoutMs });
|
|
79
|
+
await page.locator("body").waitFor({ state: "visible", timeout: timeoutMs });
|
|
80
|
+
assertSameOrigin(page, base);
|
|
81
|
+
} else if (step.action === "assertAuthenticated") {
|
|
82
|
+
const sitePath = base.pathname.replace(/\/$/, "");
|
|
83
|
+
const apiPath = `${sitePath}/_api/web/currentuser?$select=Id`;
|
|
84
|
+
const result = await page.evaluate(async (path) => {
|
|
85
|
+
const response = await fetch(path, {
|
|
86
|
+
credentials: "same-origin",
|
|
87
|
+
headers: { Accept: "application/json;odata=nometadata" },
|
|
88
|
+
});
|
|
89
|
+
return { status: response.status, contentType: response.headers.get("content-type") ?? "" };
|
|
90
|
+
}, apiPath);
|
|
91
|
+
if (result.status < 200 || result.status >= 300 || !result.contentType.toLowerCase().includes("json")) {
|
|
92
|
+
throw new Error(`Signed-in SharePoint REST check failed (HTTP ${result.status}).`);
|
|
93
|
+
}
|
|
94
|
+
assertSameOrigin(page, base);
|
|
95
|
+
} else if (step.action === "click") {
|
|
96
|
+
await locatorFor(page, step.locator).click({ timeout: timeoutMs });
|
|
97
|
+
assertSameOrigin(page, base);
|
|
98
|
+
} else if (step.action === "fill") {
|
|
99
|
+
await locatorFor(page, step.locator).fill(step.value, { timeout: timeoutMs });
|
|
100
|
+
assertSameOrigin(page, base);
|
|
101
|
+
} else if (step.action === "select") {
|
|
102
|
+
await locatorFor(page, step.locator).selectOption(step.value, { timeout: timeoutMs });
|
|
103
|
+
assertSameOrigin(page, base);
|
|
104
|
+
} else if (step.action === "setChecked") {
|
|
105
|
+
await locatorFor(page, step.locator).setChecked(step.checked, { timeout: timeoutMs });
|
|
106
|
+
assertSameOrigin(page, base);
|
|
107
|
+
} else if (step.action === "assertVisible") {
|
|
108
|
+
await locatorFor(page, step.locator).waitFor({ state: "visible", timeout: timeoutMs });
|
|
109
|
+
assertSameOrigin(page, base);
|
|
110
|
+
} else if (step.action === "assertText") {
|
|
111
|
+
const target = locatorFor(page, step.locator);
|
|
112
|
+
await target.waitFor({ state: "visible", timeout: timeoutMs });
|
|
113
|
+
const actual = (await target.innerText()).replace(/\s+/g, " ").trim();
|
|
114
|
+
const expected = step.expected.replace(/\s+/g, " ").trim();
|
|
115
|
+
if (!(step.exact ? actual === expected : actual.includes(expected))) throw new Error(`Text assertion failed (${step.exact ? "exact" : "contains"}).`);
|
|
116
|
+
assertSameOrigin(page, base);
|
|
117
|
+
} else if (step.action === "assertValue") {
|
|
118
|
+
const target = locatorFor(page, step.locator);
|
|
119
|
+
await target.waitFor({ state: "visible", timeout: timeoutMs });
|
|
120
|
+
const actual = await target.inputValue();
|
|
121
|
+
if (!(step.exact === false ? actual.includes(step.expected) : actual === step.expected)) throw new Error(`Value assertion failed (${step.exact === false ? "contains" : "exact"}).`);
|
|
122
|
+
assertSameOrigin(page, base);
|
|
123
|
+
} else if (step.action === "screenshot") {
|
|
124
|
+
if (!screenshotDir) throw new Error("Screenshots need an artifact directory.");
|
|
125
|
+
assertSameOrigin(page, base);
|
|
126
|
+
const file = join(screenshotDir, `${step.name}.png`);
|
|
127
|
+
await page.screenshot({ path: file, fullPage: step.fullPage ?? false });
|
|
128
|
+
screenshots.push(file);
|
|
129
|
+
}
|
|
130
|
+
} catch (cause) {
|
|
131
|
+
const error = new Error(`Recipe step ${index + 1} (${step.action}) failed.`, { cause });
|
|
132
|
+
error.step = index + 1;
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return { name: recipe.name, steps: recipe.steps.length, screenshots };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function generateTestSource(recipe) {
|
|
140
|
+
validateRecipe(recipe);
|
|
141
|
+
return `import { test } from "@playwright/test";\nimport { runRecipe } from "@spfx-fast/playwright";\n\nconst recipe = ${JSON.stringify(recipe, null, 2)};\n\ntest(recipe.name, async ({ page }, testInfo) => {\n const baseUrl = process.env.SPFX_BASE_URL;\n if (!baseUrl) throw new Error("Set SPFX_BASE_URL to the SharePoint site under test.");\n await runRecipe(page, recipe, {\n baseUrl,\n screenshotDir: testInfo.outputPath("spfx-fast-screenshots"),\n });\n});\n`;
|
|
142
|
+
}
|