@testspectra/cli 1.1.8-rc.18 → 1.1.8-rc.20

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.
@@ -12,8 +12,8 @@
12
12
  "postinstall": "spectra sync-types"
13
13
  },
14
14
  "devDependencies": {
15
- "@testspectra/cli": "^1.1.8-rc.18",
16
- "@testspectra/matchers": "^1.1.8-rc.18",
15
+ "@testspectra/cli": "^1.1.8-rc.20",
16
+ "@testspectra/matchers": "^1.1.8-rc.20",
17
17
  "@types/node": "^20.14.0",
18
18
  "@wdio/cli": "^9.2.8",
19
19
  "@wdio/local-runner": "^9.2.8",
@@ -14,9 +14,9 @@
14
14
  "postinstall": "spectra sync-types"
15
15
  },
16
16
  "devDependencies": {
17
- "@testspectra/cli": "^1.1.8-rc.18",
18
- "@testspectra/matchers": "^1.1.8-rc.18",
19
- "@testspectra/react": "^1.1.8-rc.18",
17
+ "@testspectra/cli": "^1.1.8-rc.20",
18
+ "@testspectra/matchers": "^1.1.8-rc.20",
19
+ "@testspectra/react": "^1.1.8-rc.20",
20
20
  "@types/node": "^20.14.0",
21
21
  "@types/react": "^18.3.3",
22
22
  "@types/react-dom": "^18.3.0",
@@ -1 +0,0 @@
1
- 2db95c618fc201b3c5e4b2f56e93c5e5fca36ba0d31250c65c98aabed5385361
@@ -1 +0,0 @@
1
- export {};
@@ -1,93 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
- import { cloudRunCommand, parseTimeoutMs } from '../cloud-run.js';
3
- const ORIGINAL_ENV = { ...process.env };
4
- function mockFetchSequence(responses) {
5
- let call = 0;
6
- return vi.fn(async (_url, _init) => {
7
- const res = responses[Math.min(call, responses.length - 1)];
8
- call += 1;
9
- return {
10
- ok: res.ok,
11
- status: res.status ?? (res.ok ? 200 : 500),
12
- statusText: 'error',
13
- json: async () => res.json,
14
- };
15
- });
16
- }
17
- describe('cloudRunCommand (docs/v2/cloud/git-spec-standards-and-workflow.md)', () => {
18
- beforeEach(() => {
19
- process.env = { ...ORIGINAL_ENV, SPECTRA_URL: 'https://cloud.test', SPECTRA_TOKEN: 'gitea-pat-123' };
20
- process.exitCode = undefined;
21
- vi.useFakeTimers();
22
- });
23
- afterEach(() => {
24
- process.env = { ...ORIGINAL_ENV };
25
- vi.restoreAllMocks();
26
- vi.useRealTimers();
27
- });
28
- it('fails fast without SPECTRA_URL/SPECTRA_TOKEN', async () => {
29
- delete process.env.SPECTRA_URL;
30
- delete process.env.SPECTRA_TOKEN;
31
- const fetchSpy = vi.fn();
32
- vi.stubGlobal('fetch', fetchSpy);
33
- await cloudRunCommand({ project: 'org/repo', branch: 'main' });
34
- expect(process.exitCode).toBe(1);
35
- expect(fetchSpy).not.toHaveBeenCalled();
36
- });
37
- it('triggers and returns immediately with --no-wait', async () => {
38
- const fetchSpy = mockFetchSequence([{ ok: true, json: { job_id: 'job-1', status: 'queued' } }]);
39
- vi.stubGlobal('fetch', fetchSpy);
40
- await cloudRunCommand({ project: 'org/repo', branch: 'main', wait: false });
41
- expect(fetchSpy).toHaveBeenCalledTimes(1);
42
- const [url, init] = fetchSpy.mock.calls[0];
43
- expect(url).toBe('https://cloud.test/api/v1/runs/trigger');
44
- const headers = init.headers;
45
- expect(headers.Authorization).toBe('Bearer gitea-pat-123');
46
- expect(JSON.parse(init.body)).toMatchObject({ project_id: 'org/repo', branch: 'main', platform: 'web' });
47
- expect(process.exitCode).toBeUndefined();
48
- });
49
- it('exits 0 when the job reaches done', async () => {
50
- const fetchSpy = mockFetchSequence([
51
- { ok: true, json: { job_id: 'job-2', status: 'queued' } },
52
- { ok: true, json: { status: 'done', run_id: 'run-2', started_at: null, completed_at: null, error_log: null } },
53
- ]);
54
- vi.stubGlobal('fetch', fetchSpy);
55
- const promise = cloudRunCommand({ project: 'org/repo', branch: 'main' });
56
- await vi.advanceTimersByTimeAsync(5000);
57
- await promise;
58
- expect(process.exitCode).toBe(0);
59
- });
60
- it('exits 1 when the job reaches failed', async () => {
61
- const fetchSpy = mockFetchSequence([
62
- { ok: true, json: { job_id: 'job-3', status: 'queued' } },
63
- {
64
- ok: true,
65
- json: { status: 'failed', run_id: 'run-3', started_at: null, completed_at: null, error_log: 'boom' },
66
- },
67
- ]);
68
- vi.stubGlobal('fetch', fetchSpy);
69
- const promise = cloudRunCommand({ project: 'org/repo', branch: 'main' });
70
- await vi.advanceTimersByTimeAsync(5000);
71
- await promise;
72
- expect(process.exitCode).toBe(1);
73
- });
74
- it('exits 1 when the trigger request itself fails', async () => {
75
- const fetchSpy = mockFetchSequence([{ ok: false, status: 401, json: { error: 'Invalid PAT' } }]);
76
- vi.stubGlobal('fetch', fetchSpy);
77
- await cloudRunCommand({ project: 'org/repo', branch: 'main' });
78
- expect(process.exitCode).toBe(1);
79
- });
80
- });
81
- describe('parseTimeoutMs', () => {
82
- it('parses seconds, minutes, and hours', () => {
83
- expect(parseTimeoutMs('30s')).toBe(30_000);
84
- expect(parseTimeoutMs('30m')).toBe(30 * 60_000);
85
- expect(parseTimeoutMs('2h')).toBe(2 * 3_600_000);
86
- });
87
- it('defaults to minutes when no unit is given', () => {
88
- expect(parseTimeoutMs('10')).toBe(10 * 60_000);
89
- });
90
- it('falls back to 30m for unparseable input', () => {
91
- expect(parseTimeoutMs('nonsense')).toBe(30 * 60_000);
92
- });
93
- });
@@ -1,13 +0,0 @@
1
- export interface CloudRunOptions {
2
- project: string;
3
- projectName?: string;
4
- branch?: string;
5
- commit?: string;
6
- platform?: string;
7
- wait?: boolean;
8
- timeout?: string;
9
- demo?: boolean;
10
- baseUrl?: string;
11
- }
12
- export declare function parseTimeoutMs(timeout: string): number;
13
- export declare function cloudRunCommand(options: CloudRunOptions): Promise<void>;
@@ -1,120 +0,0 @@
1
- import { execFileSync } from 'child_process';
2
- import chalk from 'chalk';
3
- import ora from 'ora';
4
- const POLL_INTERVAL_MS = 5000;
5
- const DEFAULT_TIMEOUT = '30m';
6
- function detectGitRef(...args) {
7
- try {
8
- return execFileSync('git', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || undefined;
9
- }
10
- catch {
11
- return undefined;
12
- }
13
- }
14
- export function parseTimeoutMs(timeout) {
15
- const match = /^(\d+)(s|m|h)?$/.exec(timeout.trim());
16
- if (!match)
17
- return 30 * 60 * 1000;
18
- const value = Number(match[1]);
19
- const unit = match[2] ?? 'm';
20
- const multiplier = unit === 's' ? 1000 : unit === 'h' ? 3_600_000 : 60_000;
21
- return value * multiplier;
22
- }
23
- // Same credential path as the trigger endpoint expects: a Gitea PAT, not the
24
- // dashboard's OAuth2 session — a CI runner can't complete a browser redirect.
25
- // See docs/v2/cloud/git-spec-standards-and-workflow.md.
26
- function requireEnv(name) {
27
- const value = process.env[name];
28
- if (!value) {
29
- console.error(chalk.red(`Missing required environment variable: ${name}`));
30
- console.error(chalk.gray('Set it as a CI secret — see docs/v2/cloud/git-spec-standards-and-workflow.md'));
31
- }
32
- return value;
33
- }
34
- export async function cloudRunCommand(options) {
35
- const spectraUrl = requireEnv('SPECTRA_URL')?.replace(/\/$/, '');
36
- const spectraToken = requireEnv('SPECTRA_TOKEN');
37
- if (!spectraUrl || !spectraToken) {
38
- process.exitCode = 1;
39
- return;
40
- }
41
- const branch = options.branch ?? detectGitRef('rev-parse', '--abbrev-ref', 'HEAD');
42
- if (!branch) {
43
- console.error(chalk.red('Could not determine branch: pass --branch or run inside a git repository.'));
44
- process.exitCode = 1;
45
- return;
46
- }
47
- const commit = options.commit ?? detectGitRef('rev-parse', 'HEAD');
48
- const platform = options.platform ?? 'web';
49
- const wait = options.wait !== false;
50
- const timeout = options.timeout ?? DEFAULT_TIMEOUT;
51
- const spinner = ora(`Triggering cloud run for ${chalk.bold(options.project)}@${branch}...`).start();
52
- let trigger;
53
- try {
54
- const res = await fetch(`${spectraUrl}/api/v1/runs/trigger`, {
55
- method: 'POST',
56
- headers: {
57
- 'Content-Type': 'application/json',
58
- Authorization: `Bearer ${spectraToken}`,
59
- },
60
- body: JSON.stringify({
61
- project_id: options.project,
62
- project_name: options.projectName ?? options.project,
63
- branch,
64
- commit_hash: commit,
65
- platform,
66
- demo: options.demo ?? false,
67
- base_url: options.baseUrl,
68
- }),
69
- });
70
- if (!res.ok) {
71
- const body = await res.json().catch(() => ({ error: res.statusText }));
72
- throw new Error(body.error ?? `HTTP ${res.status}`);
73
- }
74
- trigger = (await res.json());
75
- }
76
- catch (err) {
77
- spinner.fail(chalk.red(`Failed to trigger cloud run: ${err.message}`));
78
- process.exitCode = 1;
79
- return;
80
- }
81
- spinner.succeed(`Cloud run queued: ${chalk.cyan(trigger.job_id)}`);
82
- if (!wait) {
83
- console.log(chalk.gray(`Not waiting for result. Poll ${spectraUrl}/api/v1/jobs/${trigger.job_id}/status yourself.`));
84
- return;
85
- }
86
- await waitForJob(spectraUrl, spectraToken, trigger.job_id, timeout);
87
- }
88
- async function waitForJob(spectraUrl, spectraToken, jobId, timeout) {
89
- const spinner = ora('Waiting for run to finish...').start();
90
- const deadline = Date.now() + parseTimeoutMs(timeout);
91
- while (Date.now() < deadline) {
92
- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
93
- let job;
94
- try {
95
- const res = await fetch(`${spectraUrl}/api/v1/jobs/${jobId}/status`, {
96
- headers: { Authorization: `Bearer ${spectraToken}` },
97
- });
98
- if (!res.ok)
99
- throw new Error(`HTTP ${res.status}`);
100
- job = (await res.json());
101
- }
102
- catch (err) {
103
- spinner.text = chalk.yellow(`Poll failed, retrying: ${err.message}`);
104
- continue;
105
- }
106
- if (job.status === 'done') {
107
- spinner.succeed(chalk.green(`Run passed (run_id: ${job.run_id})`));
108
- process.exitCode = 0;
109
- return;
110
- }
111
- if (job.status === 'failed') {
112
- spinner.fail(chalk.red(`Run failed (run_id: ${job.run_id})${job.error_log ? `: ${job.error_log}` : ''}`));
113
- process.exitCode = 1;
114
- return;
115
- }
116
- spinner.text = `Run status: ${job.status}`;
117
- }
118
- spinner.fail(chalk.red(`Timed out after ${timeout} waiting for the run to finish.`));
119
- process.exitCode = 1;
120
- }
@@ -1,26 +0,0 @@
1
- # TestSpectra Project Architecture
2
-
3
- This project is built with the TestSpectra testing framework.
4
-
5
- ## Structure & File Map
6
- - `./spectra.config.ts`: Typed runner configuration.
7
- - `./specs/`: Layered test cases (`specs/<Suite>/<CaseId>/` with `web.test.ts`, `android.test.ts`, `ios.test.ts`).
8
- - `./page-objects/`: Page Object models per platform.
9
- - `./support/steps/`: Business flows accessible globally via `Step.*`.
10
- - `./support/actions/`: Atomic actions accessible globally via `Spectra.*`.
11
- - `./fixtures/`: JSON fixtures accessible globally via `Fixture.*`.
12
- - `./global-hooks/`: Global suite lifecycle hooks.
13
- - `./.testspectra/`: Auto-generated ambient typings and local runtime cache.
14
-
15
- ## Execution
16
- ```bash
17
- # Run web test suite
18
- pnpm test
19
-
20
- # Run Android / iOS
21
- pnpm spectra run --target android
22
- pnpm spectra run --target ios
23
-
24
- # Type check
25
- pnpm type-check
26
- ```
@@ -1,119 +0,0 @@
1
- # TestSpectra Enterprise Monorepo Architecture
2
-
3
- This workspace uses TestSpectra's **"Centralized Configuration, Distributed Implementation"** model for automated cross-platform testing.
4
-
5
- ---
6
-
7
- ## 1. Directory & File Overview
8
-
9
- ### Centralized Root Elements
10
- - `./spectra.config.ts`: Single source of truth for runtime configurations (Base URL, Appium devices, browser targets, timeouts).
11
- - `./.testspectra/`: Local test project cache, runtime metadata, auto-generated master TSConfig (`.testspectra/tsconfig.json`), platform sub-configs (`.testspectra/tsconfig/`), and universal ambient types (`.testspectra/types/`). Global binaries and drivers are managed at `~/.testspectra/drivers/`.
12
- - `./nx.json`: Nx target defaults with execution caching and inputs.
13
- - `./pnpm-workspace.yaml`: Monorepo package glob definitions.
14
- - `./tsconfig.json`: Solution-style TypeScript orchestrator referencing `./.testspectra/tsconfig.json`.
15
-
16
- ### Centralized Shared Testing Library (`./__SHARED_TESTING_REL_PATH__`)
17
- Provides cross-feature reusable test entities with **100% zero-import global resolution**:
18
- - `page-objects/`: Shared Page Object models (e.g. NavigationBar, AppHeader).
19
- - `support/steps/`: Cross-feature business step flows (e.g. `Step.loginAsAdmin()`).
20
- - `support/actions/`: Custom atomic actions (e.g. `Spectra.dismissBanner()`).
21
- - `fixtures/`: Common test data and environment configurations (e.g. `Fixture.appConfig`).
22
-
23
- ### Distributed Feature E2E Modules (__FEATURE_COUNT__ Features)
24
- __FEATURE_MODULES_SECTION__
25
-
26
- ---
27
-
28
- ## 2. Zero-Import Consumption Flow & Mechanics
29
-
30
- TestSpectra completely eliminates boilerplate `import` statements across all test specs, steps, and page objects.
31
-
32
- ### How It Works:
33
- 1. **Centralized Ambient Aggregation**:
34
- TestSpectra Language Service Plugin & CLI automatically scan:
35
- - **Local Feature Entities**: `<feature>/__E2E_FOLDER_NAME__/page-objects/`, `<feature>/__E2E_FOLDER_NAME__/support/steps/`, `<feature>/__E2E_FOLDER_NAME__/support/actions/`
36
- - **Shared Library Entities**: `./__SHARED_TESTING_REL_PATH__/page-objects/`, `./__SHARED_TESTING_REL_PATH__/support/steps/`, `./__SHARED_TESTING_REL_PATH__/support/actions/`, `./__SHARED_TESTING_REL_PATH__/fixtures/`
37
- 2. **Ambient Typing Generation**:
38
- These are compiled into `.testspectra/types/web.d.ts`, `android.d.ts`, `ios.d.ts`, `fixtures.d.ts`.
39
- 3. **Instant IDE Autocomplete & Zero Clutter**:
40
- Specs consume both local feature objects and shared library utilities globally.
41
-
42
- ### Code Example:
43
- ```typescript
44
- // packages/features/auth/e2e/specs/Auth/TC-AUTH-01/web.test.ts
45
- // 🌟 NOTICE: 100% Zero-Import & Flat Execution! (No import statement, no describe wrapper)
46
-
47
- it("should navigate via shared header and login with local POM", async () => {
48
- // 1. Consumed from Shared Testing Library (__SHARED_TESTING_REL_PATH__/page-objects/NavigationBar)
49
- await NavigationBar.goToLogin();
50
-
51
- // 2. Consumed from Shared Testing Library (__SHARED_TESTING_REL_PATH__/support/steps/loginAsAdmin)
52
- await Step.loginAsAdmin();
53
-
54
- // 3. Consumed from Local Feature POM (page-objects/LoginPage)
55
- await LoginPage.flashAlert.shouldBeVisible();
56
- await LoginPage.flashAlert.shouldContainText("Welcome");
57
-
58
- // 4. Consumed from Shared Testing Library Custom Action (__SHARED_TESTING_REL_PATH__/support/actions/dismissBanner)
59
- await Spectra.dismissBanner();
60
- });
61
- ```
62
-
63
- ---
64
-
65
- ## 3. How to Run Tests
66
-
67
- You can execute tests either from the **Monorepo Root via Nx** or directly inside each **Feature Directory via CLI**:
68
-
69
- ### Option A: From Root Monorepo via Nx (Recommended for CI & Team Workflows)
70
-
71
- ```bash
72
- # 1. Run E2E for a SPECIFIC feature module (e.g. auth)
73
- pnpm nx run auth-__E2E_FOLDER_NAME__:e2e
74
-
75
- # 2. Run E2E for a specific feature on ANDROID or IOS
76
- pnpm nx run auth-__E2E_FOLDER_NAME__:e2e --configuration=android
77
- pnpm nx run auth-__E2E_FOLDER_NAME__:e2e --configuration=ios
78
-
79
- # 3. Run E2E for a specific feature in HEADLESS browser mode
80
- pnpm nx run auth-__E2E_FOLDER_NAME__:e2e --configuration=headless
81
-
82
- # 4. Run ALL feature E2E suites across the entire monorepo in parallel
83
- pnpm nx run-many -t e2e
84
-
85
- # 5. Run only E2E tests for features modified in current Git branch / PR
86
- pnpm nx affected -t e2e
87
- ```
88
-
89
- ### Option B: From Inside the Feature Directory (Direct CLI)
90
-
91
- ```bash
92
- # Navigate to the feature e2e folder
93
- cd __SAMPLE_FEATURE_E2E_PATH__
94
-
95
- # Run all specs in this feature
96
- pnpm spectra run
97
-
98
- # Run a specific test case file
99
- pnpm spectra run specs/Auth/TC-AUTH-01/web.test.ts
100
-
101
- # Target Android device or emulator
102
- pnpm spectra run --target android
103
-
104
- # Run in headed / interactive browser mode
105
- pnpm spectra run --no-headless
106
- ```
107
-
108
- ---
109
-
110
- ## 4. Type Checking & Validation
111
-
112
- ```bash
113
- # Type check all E2E projects via Nx
114
- pnpm nx run-many -t type-check
115
-
116
- # Or standard TypeScript project references build from root
117
- pnpm type-check
118
- # or: npx tsc -b
119
- ```