@dxos/test-utils 0.10.0 → 0.11.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,12 @@
1
+ import { onTestFinished } from "vitest";
2
+ //#region src/resource.ts
3
+ var openAndClose = async (...resources) => {
4
+ for (const resourceLike of resources) {
5
+ await resourceLike.open();
6
+ onTestFinished(() => resourceLike.close());
7
+ }
8
+ };
9
+ //#endregion
10
+ export { openAndClose };
11
+
12
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/resource.ts"],"sourcesContent":["//\n// Copyright 2023 DXOS.org\n//\n\nimport { onTestFinished } from 'vitest';\n\ninterface ResourceLike {\n open(): Promise<any>;\n close(): Promise<any>;\n}\n\n// TODO(burdon): Replace with abstraction relating to Context object?\nexport const openAndClose = async (...resources: ResourceLike[]) => {\n for (const resourceLike of resources) {\n await resourceLike.open();\n onTestFinished(() => resourceLike.close());\n }\n};\n"],"mappings":";;AAYA,IAAa,eAAe,OAAO,GAAG,cAA8B;CAClE,KAAK,MAAM,gBAAgB,WAAW;EACpC,MAAM,aAAa,KAAK;EACxB,qBAAqB,aAAa,MAAM,CAAC;CAC3C;AACF"}
@@ -0,0 +1,116 @@
1
+ import { devices } from "@playwright/test";
2
+ import { existsSync, readFileSync } from "@dxos/node-std/fs";
3
+ import { dirname, join, resolve } from "@dxos/node-std/path";
4
+ import pkgUp from "pkg-up";
5
+ import { trigger } from "@dxos/async";
6
+ //#region src/lock.ts
7
+ var Lock = class {
8
+ _lastPromise = Promise.resolve();
9
+ async executeSynchronized(fun) {
10
+ const prevPromise = this._lastPromise;
11
+ const [getPromise, resolve] = trigger();
12
+ this._lastPromise = getPromise();
13
+ await prevPromise;
14
+ try {
15
+ return await fun();
16
+ } finally {
17
+ resolve();
18
+ }
19
+ }
20
+ };
21
+ //#endregion
22
+ //#region src/playwright.ts
23
+ var findWorkspaceRoot = (startDir) => {
24
+ let dir = resolve(startDir);
25
+ while (dir !== "/") {
26
+ try {
27
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
28
+ const pkgPath = join(dir, "package.json");
29
+ if (JSON.parse(readFileSync(pkgPath, "utf-8")).workspaces) return dir;
30
+ } catch {}
31
+ const parent = dirname(dir);
32
+ if (parent === dir) break;
33
+ dir = parent;
34
+ }
35
+ throw new Error("Could not find pnpm workspace root");
36
+ };
37
+ var e2ePreset = (testDir) => {
38
+ const packageDir = pkgUp.sync({ cwd: testDir }).split("/").slice(0, -1).join("/");
39
+ const packageDirName = packageDir.split("/").pop();
40
+ if (!packageDirName) throw new Error("packageDirName not found");
41
+ const workspaceRoot = findWorkspaceRoot(packageDir);
42
+ const testResultOuputDir = join(workspaceRoot, "test-results/playwright/output", packageDirName);
43
+ const reporterOutputFile = join(workspaceRoot, "test-results/playwright/report", `${packageDirName}.json`);
44
+ const browser = process.env.PLAYWRIGHT_BROWSER || (process.env.CI ? "all" : "chromium");
45
+ const projects = [
46
+ {
47
+ name: "chromium",
48
+ use: { ...devices["Desktop Chrome"] }
49
+ },
50
+ {
51
+ name: "firefox",
52
+ use: { ...devices["Desktop Firefox"] }
53
+ },
54
+ {
55
+ name: "webkit",
56
+ use: { ...devices["Desktop Safari"] }
57
+ }
58
+ ].filter((project) => {
59
+ return browser === "all" || project.name === browser;
60
+ });
61
+ return {
62
+ testDir,
63
+ outputDir: testResultOuputDir,
64
+ timeout: 6e4,
65
+ fullyParallel: true,
66
+ forbidOnly: !!process.env.CI,
67
+ retries: process.env.CI ? 2 : 0,
68
+ workers: process.env.CI ? 1 : 4,
69
+ reporter: process.env.CI ? [
70
+ ["list"],
71
+ ["json", { outputFile: reporterOutputFile }],
72
+ ["junit", { outputFile: reporterOutputFile.replace(/\.json$/, ".xml") }]
73
+ ] : [["list"]],
74
+ use: {
75
+ trace: "retain-on-failure",
76
+ actionTimeout: 3e4
77
+ },
78
+ projects
79
+ };
80
+ };
81
+ var setupPage = async (browser, options = {}) => {
82
+ const { url, bridgeLogs, viewportSize } = options;
83
+ const context = "newContext" in browser ? await browser.newContext() : browser;
84
+ const page = await context.newPage();
85
+ if (viewportSize) await page.setViewportSize(viewportSize);
86
+ if (bridgeLogs) {
87
+ const lock = new Lock();
88
+ page.on("pageerror", async (error) => {
89
+ await lock.executeSynchronized(async () => {
90
+ console.log(error);
91
+ });
92
+ });
93
+ page.on("console", async (msg) => {
94
+ try {
95
+ const argsPromise = Promise.all(msg.args().map((x) => x.jsonValue()));
96
+ await lock.executeSynchronized(async () => {
97
+ const args = await argsPromise;
98
+ if (args.length > 0) console.log(...args);
99
+ else console.log(msg);
100
+ });
101
+ } catch (err) {
102
+ console.error("Failed to parse message", err);
103
+ }
104
+ });
105
+ }
106
+ if (url) await page.goto(url);
107
+ return {
108
+ context,
109
+ page
110
+ };
111
+ };
112
+ var storybookUrl = (storyId, port = 9009) => `http://localhost:${port}/iframe.html?id=${storyId}&viewMode=story`;
113
+ //#endregion
114
+ export { e2ePreset, setupPage, storybookUrl };
115
+
116
+ //# sourceMappingURL=playwright.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"playwright.mjs","names":[],"sources":["../../src/lock.ts","../../src/playwright.ts"],"sourcesContent":["//\n// Copyright 2022 DXOS.org\n//\n\nimport { trigger } from '@dxos/async';\n\n// Copied from @dxos/async.\nexport class Lock {\n private _lastPromise = Promise.resolve();\n\n async executeSynchronized<T>(fun: () => Promise<T>): Promise<T> {\n const prevPromise = this._lastPromise;\n const [getPromise, resolve] = trigger();\n this._lastPromise = getPromise();\n\n await prevPromise;\n try {\n const value = await fun();\n return value;\n } finally {\n resolve();\n }\n }\n}\n","//\n// Copyright 2023 DXOS.org\n//\n\n/* eslint-disable no-console */\n\nimport { type Browser, type BrowserContext, type Page, type PlaywrightTestConfig, devices } from '@playwright/test';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport pkgUp from 'pkg-up';\n\nimport { Lock } from './lock';\n\nconst findWorkspaceRoot = (startDir: string): string => {\n let dir = resolve(startDir);\n while (dir !== '/') {\n try {\n // Check for pnpm-workspace.yaml first (modern pnpm approach)\n const workspaceYamlPath = join(dir, 'pnpm-workspace.yaml');\n if (existsSync(workspaceYamlPath)) {\n return dir;\n }\n\n // Check for package.json with workspaces field (legacy approach)\n const pkgPath = join(dir, 'package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n if (pkg.workspaces) {\n return dir;\n }\n } catch {}\n const parent = dirname(dir);\n if (parent === dir) {\n break;\n }\n dir = parent;\n }\n\n throw new Error('Could not find pnpm workspace root');\n};\n\nexport const e2ePreset = (testDir: string): PlaywrightTestConfig => {\n const packageJson = pkgUp.sync({ cwd: testDir });\n const packageDir = packageJson!.split('/').slice(0, -1).join('/');\n const packageDirName = packageDir.split('/').pop();\n if (!packageDirName) {\n throw new Error('packageDirName not found');\n }\n\n const workspaceRoot = findWorkspaceRoot(packageDir);\n const testResultOuputDir = join(workspaceRoot, 'test-results/playwright/output', packageDirName);\n const reporterOutputFile = join(workspaceRoot, 'test-results/playwright/report', `${packageDirName}.json`);\n\n const browser = process.env.PLAYWRIGHT_BROWSER || (process.env.CI ? 'all' : 'chromium');\n const projects = [\n {\n name: 'chromium',\n use: { ...devices['Desktop Chrome'] },\n },\n {\n name: 'firefox',\n use: { ...devices['Desktop Firefox'] },\n },\n {\n name: 'webkit',\n use: { ...devices['Desktop Safari'] },\n },\n ].filter((project) => {\n return browser === 'all' || project.name === browser;\n });\n\n return {\n testDir,\n outputDir: testResultOuputDir,\n // Playwright's default is 30s, which equals the action bound below — leaving a test no budget beyond\n // a single slow action. Storybook-backed suites also pay an on-demand story compile in the first\n // test's `beforeEach`, which alone exceeded 30s. Individual configs may still raise this.\n timeout: 60_000,\n // Run tests in files in parallel.\n fullyParallel: true,\n // Fail the build on CI if you accidentally left test.only in the source code.\n forbidOnly: !!process.env.CI,\n // Retry on CI to ride out the residual d&d / startup flakes while the\n // underlying causes are still being chased. Local runs stay strict so\n // flakes are visible while iterating.\n retries: process.env.CI ? 2 : 0,\n // Opt out of parallel tests on CI.\n workers: process.env.CI ? 1 : 4,\n // Reporter to use. See https://playwright.dev/docs/test-reporters.\n reporter: process.env.CI\n ? [\n ['list'],\n [\n 'json',\n {\n outputFile: reporterOutputFile,\n },\n ],\n ['junit', { outputFile: reporterOutputFile.replace(/\\.json$/, '.xml') }],\n ]\n : [['list']],\n use: {\n trace: 'retain-on-failure',\n // Playwright's default is no limit, so a stuck locator would absorb the whole per-test budget and\n // report a bare `Test timeout` naming nothing.\n actionTimeout: 30_000,\n },\n projects,\n };\n};\n\nexport type SetupOptions = {\n url?: string;\n bridgeLogs?: boolean;\n viewportSize?: Parameters<Page['setViewportSize']>[0];\n};\n\nexport const setupPage = async (browser: Browser | BrowserContext, options: SetupOptions = {}) => {\n const { url, bridgeLogs, viewportSize } = options;\n\n const context = 'newContext' in browser ? await browser.newContext() : browser;\n const page = await context.newPage();\n\n if (viewportSize) {\n await page.setViewportSize(viewportSize);\n }\n\n // TODO(wittjosiah): Remove?\n if (bridgeLogs) {\n const lock = new Lock();\n\n page.on('pageerror', async (error) => {\n await lock.executeSynchronized(async () => {\n // eslint-disable-next-line no-console\n console.log(error);\n });\n });\n\n page.on('console', async (msg) => {\n try {\n const argsPromise = Promise.all(msg.args().map((x) => x.jsonValue()));\n await lock.executeSynchronized(async () => {\n const args = await argsPromise;\n\n if (args.length > 0) {\n console.log(...args);\n } else {\n console.log(msg);\n }\n });\n } catch (err) {\n console.error('Failed to parse message', err);\n }\n });\n }\n\n if (url) {\n await page.goto(url);\n }\n\n return { context, page };\n};\n\nexport const storybookUrl = (storyId: string, port = 9009) =>\n `http://localhost:${port}/iframe.html?id=${storyId}&viewMode=story`;\n"],"mappings":";;;;;;AAOA,IAAa,OAAb,MAAkB;CAChB,eAAuB,QAAQ,QAAQ;CAEvC,MAAM,oBAAuB,KAAmC;EAC9D,MAAM,cAAc,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AAC;CACH;CAEA,IAAI,KACF,MAAM,KAAK,KAAK,GAAG;CAGrB,OAAO;EAAE;EAAS;CAAK;AACzB;AAEA,IAAa,gBAAgB,SAAiB,OAAO,SACnD,oBAAoB,KAAK,kBAAkB,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"playwright.d.ts","sourceRoot":"","sources":["../../../src/playwright.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,IAAI,EAAE,KAAK,oBAAoB,EAAW,MAAM,kBAAkB,CAAC;AAkCpH,eAAO,MAAM,SAAS,YAAa,MAAM,KAAG,oBA6D3C,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,YAAY,CAAC,EAAE,UAAU,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CACvD,CAAC;AAEF,eAAO,MAAM,SAAS,YAAmB,OAAO,GAAG,cAAc,YAAW,YAAY;;;EA4CvF,CAAC;AAEF,eAAO,MAAM,YAAY,YAAa,MAAM,0BACyB,CAAC"}
1
+ {"version":3,"file":"playwright.d.ts","sourceRoot":"","sources":["../../../src/playwright.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,IAAI,EAAE,KAAK,oBAAoB,EAAW,MAAM,kBAAkB,CAAC;AAkCpH,eAAO,MAAM,SAAS,YAAa,MAAM,KAAG,oBAoE3C,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,YAAY,CAAC,EAAE,UAAU,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CACvD,CAAC;AAEF,eAAO,MAAM,SAAS,YAAmB,OAAO,GAAG,cAAc,YAAW,YAAY;;;EA4CvF,CAAC;AAEF,eAAO,MAAM,YAAY,YAAa,MAAM,0BACyB,CAAC"}