@testspectra/cli 1.1.0-rc.0 → 1.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/bin/.testspectra-runner.hash +1 -0
  2. package/bin/testspectra-runner +0 -0
  3. package/demo-app/assets/index-DOtRypCa.js +154 -0
  4. package/demo-app/index.html +1 -1
  5. package/dist/.tsbuildinfo +1 -1
  6. package/dist/commands/__tests__/run.test.js +9 -13
  7. package/dist/commands/init.d.ts +1 -1
  8. package/dist/commands/init.js +6 -1
  9. package/dist/commands/run.js +1 -0
  10. package/dist/commands/sync-types.js +1 -0
  11. package/dist/commands/test.d.ts +17 -0
  12. package/dist/commands/test.js +76 -0
  13. package/dist/commands/watch.js +9 -2
  14. package/dist/config/loader.js +1 -1
  15. package/dist/config/schema.d.ts +5 -109
  16. package/dist/config/schema.js +1 -16
  17. package/dist/generator/__tests__/tsconfig-isolation.test.js +6 -2
  18. package/dist/generator/tsconfig-generator.js +42 -7
  19. package/dist/generator/type-generator.d.ts +24 -1
  20. package/dist/generator/type-generator.js +104 -8
  21. package/dist/index.js +15 -1
  22. package/dist/linter/__tests__/component-test-imports.test.d.ts +1 -0
  23. package/dist/linter/__tests__/component-test-imports.test.js +115 -0
  24. package/dist/linter/extractor.d.ts +1 -0
  25. package/dist/linter/extractor.js +11 -1
  26. package/dist/linter/schemas/spec.schema.d.ts +12 -12
  27. package/dist/linter/schemas/suite.schema.d.ts +8 -8
  28. package/dist/linter/spec-linter.js +38 -3
  29. package/dist/reporter/semantic-formatter.js +17 -2
  30. package/dist/reporter/types.d.ts +1 -1
  31. package/dist/runner/reporter.js +7 -3
  32. package/dist/utils/api-server.js +46 -1
  33. package/package.json +4 -3
  34. package/templates/default/package.json +2 -2
  35. package/templates/default/page-objects/AuthPage/mobile.ts +5 -0
  36. package/templates/default/page-objects/AuthPage/web.ts +10 -0
  37. package/templates/default/page-objects/MatchersPage/mobile.ts +13 -0
  38. package/templates/default/page-objects/MatchersPage/web.ts +5 -0
  39. package/templates/default/page-objects/PlaygroundPage/mobile.ts +6 -0
  40. package/templates/default/specs/ApiInterception/TC-0012-direct-and-late-response/common.test.ts +6 -9
  41. package/templates/default/specs/Authentication/TC-0021-seed-authenticated-session/mobile.test.ts +7 -0
  42. package/templates/default/specs/Authentication/TC-0021-seed-authenticated-session/spec.md +19 -0
  43. package/templates/default/specs/Authentication/TC-0021-seed-authenticated-session/web.test.ts +9 -0
  44. package/templates/default/specs/Authentication/suite.md +9 -0
  45. package/templates/default/specs/BrowserContext/TC-0022-history-navigation/mobile.test.ts +17 -0
  46. package/templates/default/specs/BrowserContext/TC-0022-history-navigation/spec.md +28 -0
  47. package/templates/default/specs/BrowserContext/TC-0022-history-navigation/web.test.ts +26 -0
  48. package/templates/default/specs/ContentMatchers/TC-0020-scoped-element-access/common.test.ts +14 -0
  49. package/templates/default/specs/ContentMatchers/TC-0020-scoped-element-access/spec.md +21 -0
  50. package/templates/default/specs/EnvironmentConfig/TC-0019-read-custom-environment-variable/common.test.ts +5 -0
  51. package/templates/default/specs/EnvironmentConfig/TC-0019-read-custom-environment-variable/spec.md +16 -0
  52. package/templates/default/specs/EnvironmentConfig/suite.md +9 -0
  53. package/templates/default/spectra.config.ts +1 -16
  54. package/templates/default/support/actions/seedSession/mobile.action.ts +9 -0
  55. package/templates/default/support/actions/seedSession/web.action.ts +13 -0
  56. package/templates/nx/.nx/workspace-data/70094CFD-E89B-57A1-9619-2FC5F4963C54.db-shm +0 -0
  57. package/templates/nx/.nx/workspace-data/70094CFD-E89B-57A1-9619-2FC5F4963C54.db-wal +0 -0
  58. package/templates/nx/.nx/workspace-data/d/daemon.log +1060 -0
  59. package/templates/nx/.nx/workspace-data/d/server-process.json +1 -1
  60. package/templates/nx/.nx/workspace-data/file-map.json +116 -104
  61. package/templates/nx/.nx/workspace-data/nx_files.nxt +0 -0
  62. package/templates/nx/package.json +2 -2
  63. package/templates/nx/packages/matchers/e2e/specs/EnvironmentConfig/TC-0019-read-custom-environment-variable/common.test.ts +5 -0
  64. package/templates/nx/packages/matchers/e2e/specs/EnvironmentConfig/TC-0019-read-custom-environment-variable/spec.md +16 -0
  65. package/templates/nx/packages/matchers/e2e/specs/EnvironmentConfig/suite.md +9 -0
  66. package/templates/nx/spectra.config.ts +1 -16
  67. package/templates/react-component/.cursorrules +17 -0
  68. package/templates/react-component/.vscode/extensions.json +5 -0
  69. package/templates/react-component/CLAUDE.md +14 -0
  70. package/templates/react-component/README.md +69 -0
  71. package/templates/react-component/fixtures/component-mock.json +12 -0
  72. package/templates/react-component/global-hooks/after/web.hook.ts +3 -0
  73. package/templates/react-component/global-hooks/before/web.hook.ts +3 -0
  74. package/templates/react-component/package.json +27 -0
  75. package/templates/react-component/page-objects/BadgeComponent/web.ts +23 -0
  76. package/templates/react-component/page-objects/ButtonComponent/web.ts +23 -0
  77. package/templates/react-component/page-objects/InputComponent/web.ts +13 -0
  78. package/templates/react-component/specs/BadgeComponent/TC-0002-badge-severities-and-dot/spec.md +18 -0
  79. package/templates/react-component/specs/BadgeComponent/TC-0002-badge-severities-and-dot/web.test.tsx +11 -0
  80. package/templates/react-component/specs/BadgeComponent/TC-0006-badge-success-with-dot/spec.md +18 -0
  81. package/templates/react-component/specs/BadgeComponent/TC-0006-badge-success-with-dot/web.test.tsx +10 -0
  82. package/templates/react-component/specs/BadgeComponent/TC-0007-badge-by-severity-lookup/spec.md +18 -0
  83. package/templates/react-component/specs/BadgeComponent/TC-0007-badge-by-severity-lookup/web.test.tsx +16 -0
  84. package/templates/react-component/specs/BadgeComponent/suite.md +12 -0
  85. package/templates/react-component/specs/ButtonComponent/TC-0001-button-rendering-and-click/spec.md +19 -0
  86. package/templates/react-component/specs/ButtonComponent/TC-0001-button-rendering-and-click/web.test.tsx +28 -0
  87. package/templates/react-component/specs/ButtonComponent/TC-0004-disabled-button-not-clickable/spec.md +19 -0
  88. package/templates/react-component/specs/ButtonComponent/TC-0004-disabled-button-not-clickable/web.test.tsx +22 -0
  89. package/templates/react-component/specs/ButtonComponent/TC-0005-button-renders-icon/spec.md +18 -0
  90. package/templates/react-component/specs/ButtonComponent/TC-0005-button-renders-icon/web.test.tsx +8 -0
  91. package/templates/react-component/specs/ButtonComponent/suite.md +12 -0
  92. package/templates/react-component/specs/InputComponent/TC-0003-input-typing-and-clear/spec.md +20 -0
  93. package/templates/react-component/specs/InputComponent/TC-0003-input-typing-and-clear/web.test.tsx +28 -0
  94. package/templates/react-component/specs/InputComponent/TC-0008-disabled-input-not-editable/spec.md +18 -0
  95. package/templates/react-component/specs/InputComponent/TC-0008-disabled-input-not-editable/web.test.tsx +9 -0
  96. package/templates/react-component/specs/InputComponent/suite.md +12 -0
  97. package/templates/react-component/spectra.config.ts +27 -0
  98. package/templates/react-component/src/components/Badge/Badge.tsx +60 -0
  99. package/templates/react-component/src/components/Button/Button.tsx +57 -0
  100. package/templates/react-component/src/components/Input/Input.tsx +41 -0
  101. package/templates/react-component/src/test-utils.tsx +23 -0
  102. package/templates/react-component/support/actions/fillInputField/web.action.ts +9 -0
  103. package/templates/react-component/support/steps/verifyButtonState/web.step.ts +12 -0
  104. package/templates/react-component/tsconfig.json +8 -0
  105. package/demo-app/assets/index-BGllUp7o.js +0 -140
@@ -41,20 +41,28 @@ export class TsConfigGenerator {
41
41
  target: 'ES2022',
42
42
  module: 'NodeNext',
43
43
  moduleResolution: 'NodeNext',
44
+ jsx: 'react-jsx',
44
45
  composite: true,
45
46
  noEmit: true,
46
47
  skipLibCheck: true,
47
48
  strict: true,
48
- types: ['node', '@wdio/globals/types', '@wdio/mocha-framework'],
49
+ types: ['node'],
49
50
  },
50
51
  include: [
51
52
  '../types/web.d.ts',
52
53
  '../types/fixtures.d.ts',
53
54
  '../../**/specs/**/*.ts',
55
+ '../../**/specs/**/*.tsx',
54
56
  '../../**/page-objects/**/*.ts',
57
+ '../../**/page-objects/**/*.tsx',
55
58
  '../../**/support/**/*.ts',
59
+ '../../**/support/**/*.tsx',
56
60
  '../../**/global-hooks/**/*.ts',
61
+ '../../**/global-hooks/**/*.tsx',
57
62
  '../../**/fixtures/**/*.ts',
63
+ '../../**/fixtures/**/*.json',
64
+ '../../**/src/**/*.ts',
65
+ '../../**/src/**/*.tsx',
58
66
  '../../spectra.config.ts',
59
67
  ],
60
68
  exclude: [
@@ -73,20 +81,28 @@ export class TsConfigGenerator {
73
81
  target: 'ES2022',
74
82
  module: 'NodeNext',
75
83
  moduleResolution: 'NodeNext',
84
+ jsx: 'react-jsx',
76
85
  composite: true,
77
86
  noEmit: true,
78
87
  skipLibCheck: true,
79
88
  strict: true,
80
- types: ['node', '@wdio/globals/types', '@wdio/mocha-framework'],
89
+ types: ['node'],
81
90
  },
82
91
  include: [
83
92
  '../types/mobile.d.ts',
84
93
  '../types/fixtures.d.ts',
85
94
  '../../**/specs/**/*.ts',
95
+ '../../**/specs/**/*.tsx',
86
96
  '../../**/page-objects/**/*.ts',
97
+ '../../**/page-objects/**/*.tsx',
87
98
  '../../**/support/**/*.ts',
99
+ '../../**/support/**/*.tsx',
88
100
  '../../**/global-hooks/**/*.ts',
101
+ '../../**/global-hooks/**/*.tsx',
89
102
  '../../**/fixtures/**/*.ts',
103
+ '../../**/fixtures/**/*.json',
104
+ '../../**/src/**/*.ts',
105
+ '../../**/src/**/*.tsx',
90
106
  '../../spectra.config.ts',
91
107
  ],
92
108
  exclude: [
@@ -105,20 +121,28 @@ export class TsConfigGenerator {
105
121
  target: 'ES2022',
106
122
  module: 'NodeNext',
107
123
  moduleResolution: 'NodeNext',
124
+ jsx: 'react-jsx',
108
125
  composite: true,
109
126
  noEmit: true,
110
127
  skipLibCheck: true,
111
128
  strict: true,
112
- types: ['node', '@wdio/globals/types', '@wdio/mocha-framework'],
129
+ types: ['node'],
113
130
  },
114
131
  include: [
115
132
  '../types/android.d.ts',
116
133
  '../types/fixtures.d.ts',
117
134
  '../../**/specs/**/*.ts',
135
+ '../../**/specs/**/*.tsx',
118
136
  '../../**/page-objects/**/*.ts',
137
+ '../../**/page-objects/**/*.tsx',
119
138
  '../../**/support/**/*.ts',
139
+ '../../**/support/**/*.tsx',
120
140
  '../../**/global-hooks/**/*.ts',
141
+ '../../**/global-hooks/**/*.tsx',
121
142
  '../../**/fixtures/**/*.ts',
143
+ '../../**/fixtures/**/*.json',
144
+ '../../**/src/**/*.ts',
145
+ '../../**/src/**/*.tsx',
122
146
  '../../spectra.config.ts',
123
147
  ],
124
148
  exclude: [
@@ -137,20 +161,28 @@ export class TsConfigGenerator {
137
161
  target: 'ES2022',
138
162
  module: 'NodeNext',
139
163
  moduleResolution: 'NodeNext',
164
+ jsx: 'react-jsx',
140
165
  composite: true,
141
166
  noEmit: true,
142
167
  skipLibCheck: true,
143
168
  strict: true,
144
- types: ['node', '@wdio/globals/types', '@wdio/mocha-framework'],
169
+ types: ['node'],
145
170
  },
146
171
  include: [
147
172
  '../types/ios.d.ts',
148
173
  '../types/fixtures.d.ts',
149
174
  '../../**/specs/**/*.ts',
175
+ '../../**/specs/**/*.tsx',
150
176
  '../../**/page-objects/**/*.ts',
177
+ '../../**/page-objects/**/*.tsx',
151
178
  '../../**/support/**/*.ts',
179
+ '../../**/support/**/*.tsx',
152
180
  '../../**/global-hooks/**/*.ts',
181
+ '../../**/global-hooks/**/*.tsx',
153
182
  '../../**/fixtures/**/*.ts',
183
+ '../../**/fixtures/**/*.json',
184
+ '../../**/src/**/*.ts',
185
+ '../../**/src/**/*.tsx',
154
186
  '../../spectra.config.ts',
155
187
  ],
156
188
  exclude: [
@@ -169,20 +201,23 @@ export class TsConfigGenerator {
169
201
  target: 'ES2022',
170
202
  module: 'NodeNext',
171
203
  moduleResolution: 'NodeNext',
204
+ jsx: 'react-jsx',
172
205
  composite: true,
173
206
  noEmit: true,
174
207
  skipLibCheck: true,
175
208
  strict: true,
176
- types: ['node', '@wdio/globals/types', '@wdio/mocha-framework'],
209
+ types: ['node'],
177
210
  },
178
211
  include: [
179
212
  '../types/common.d.ts',
180
213
  '../types/fixtures.d.ts',
181
214
  '../../**/page-objects/**/common.ts',
215
+ '../../**/page-objects/**/common.tsx',
182
216
  '../../**/support/**/common.*',
183
217
  '../../**/global-hooks/**/common.*',
184
218
  '../../**/specs/**/hooks/**/common.*',
185
219
  '../../**/specs/**/common.test.ts',
220
+ '../../**/specs/**/common.test.tsx',
186
221
  '../../spectra.config.ts',
187
222
  ],
188
223
  exclude: [
@@ -210,7 +245,7 @@ export class TsConfigGenerator {
210
245
  const relCache = path.relative(subConfigDir, path.join(options.cwd, '.testspectra', 'cache')).replace(/\\/g, '/');
211
246
  const platformDts = `${relTypesDir}/${platform}.d.ts`;
212
247
  const fixturesDts = `${relTypesDir}/fixtures.d.ts`;
213
- const include = [platformDts, fixturesDts, `${relScope}/**/*.ts`, relSpectraConfig];
248
+ const include = [platformDts, fixturesDts, `${relScope}/**/*.ts`, `${relScope}/**/*.tsx`, relSpectraConfig];
214
249
  const baseExcludes = [relNodeModules, relDist, relReports, relRuns, relCache];
215
250
  const stemMap = {
216
251
  web: ['android', 'ios', 'mobile'],
@@ -229,7 +264,7 @@ export class TsConfigGenerator {
229
264
  noEmit: true,
230
265
  skipLibCheck: true,
231
266
  strict: true,
232
- types: ['node', '@wdio/globals/types', '@wdio/mocha-framework'],
267
+ types: ['node'],
233
268
  },
234
269
  include,
235
270
  exclude: [...baseExcludes, ...platformExcludes],
@@ -18,11 +18,23 @@ export interface EntityScope {
18
18
  * - Directory with page-objects/support/fixtures and NO specs => Shared Scope
19
19
  */
20
20
  export declare function discoverEntityScopes(cwd: string): EntityScope[];
21
+ /**
22
+ * Detects a component-testing project (`@testspectra/react`'s Vitest browser-mode runner), via
23
+ * the same signal `cli/src/commands/test.ts` uses to gate `spectra test` itself. Used to augment
24
+ * the generated `Spectra` ambient type with `.mount()`, which only exists in that runtime.
25
+ */
26
+ export declare function isComponentTestingProject(cwd: string): boolean;
21
27
  export declare class TypeGenerator {
22
28
  /**
23
29
  * Main entry point to generate all ambient type declarations.
24
30
  */
25
31
  static generateAll(cwd: string): void;
32
+ /**
33
+ * Reloads `spectra.config.ts` and refreshes `.testspectra/types/env.d.ts` with the current
34
+ * `executionConfig.environmentVariables`. Separate from `writeDeclarationFiles`/`generateAll`
35
+ * (which must stay synchronous) because reading the config file is unavoidably async.
36
+ */
37
+ static syncEnvDeclaration(cwd: string): Promise<void>;
26
38
  /**
27
39
  * Discovers all feature directories and shared library directories.
28
40
  * Returns a map of scope -> base directory
@@ -30,7 +42,18 @@ export declare class TypeGenerator {
30
42
  static getEntityScopes(cwd: string): EntityScope[];
31
43
  static getPageObjectsDirsForScope(scopeDir: string, sharedDir?: string): string[];
32
44
  static getEntityDirsForScope(entityType: 'actions' | 'steps' | 'fixtures', scopeDir: string, sharedDir?: string): string[];
33
- static generateDeclarationsForScope(cwd: string, outputTypesDir: string, scopeDir: string, sharedDir?: string): Record<PlatformTarget, string>;
45
+ static generateDeclarationsForScope(cwd: string, outputTypesDir: string, scopeDir: string, sharedDir?: string, rootTypesDir?: string): Record<PlatformTarget, string>;
34
46
  static generateFixturesDeclarationForScope(cwd: string, outputTypesDir: string, scopeDir: string, sharedDir?: string): string;
47
+ /**
48
+ * Generates the typed `Spectra.env` ambient declaration from `spectra.config.ts`'s
49
+ * `executionConfig.environmentVariables` — mirrors `generateFixturesDeclarationForScope`, but
50
+ * env vars come from a single project-level config rather than a scanned directory.
51
+ *
52
+ * Emits a bare global `interface SpectraEnv { readonly KEY: string; ... }`, which TypeScript
53
+ * interface-merges with the empty `SpectraEnv` shipped by `@testspectra/matchers` (the same
54
+ * mechanism `@types/node` uses for projects to augment `NodeJS.ProcessEnv`) — so `Spectra.env.KEY`
55
+ * resolves to `string`, never `string | undefined` like raw `process.env.KEY`.
56
+ */
57
+ static generateEnvDeclaration(environmentVariables: Record<string, string>): string;
35
58
  static writeDeclarationFiles(cwd: string): void;
36
59
  }
@@ -1,5 +1,6 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
+ import { ConfigLoader } from '../config/loader.js';
3
4
  import { TsConfigGenerator } from './tsconfig-generator.js';
4
5
  export const PLATFORM_HIERARCHY = {
5
6
  web: ['web', 'common'],
@@ -180,6 +181,23 @@ export function discoverEntityScopes(cwd) {
180
181
  fallbackScan(cwd, 5);
181
182
  return scopes;
182
183
  }
184
+ /**
185
+ * Detects a component-testing project (`@testspectra/react`'s Vitest browser-mode runner), via
186
+ * the same signal `cli/src/commands/test.ts` uses to gate `spectra test` itself. Used to augment
187
+ * the generated `Spectra` ambient type with `.mount()`, which only exists in that runtime.
188
+ */
189
+ export function isComponentTestingProject(cwd) {
190
+ try {
191
+ const pkgPath = path.join(cwd, 'package.json');
192
+ if (!fs.existsSync(pkgPath))
193
+ return false;
194
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
195
+ return Boolean(pkg.dependencies?.['@testspectra/react'] || pkg.devDependencies?.['@testspectra/react']);
196
+ }
197
+ catch {
198
+ return false;
199
+ }
200
+ }
183
201
  export class TypeGenerator {
184
202
  /**
185
203
  * Main entry point to generate all ambient type declarations.
@@ -188,6 +206,24 @@ export class TypeGenerator {
188
206
  this.writeDeclarationFiles(cwd);
189
207
  TsConfigGenerator.scaffoldConfigs(cwd);
190
208
  }
209
+ /**
210
+ * Reloads `spectra.config.ts` and refreshes `.testspectra/types/env.d.ts` with the current
211
+ * `executionConfig.environmentVariables`. Separate from `writeDeclarationFiles`/`generateAll`
212
+ * (which must stay synchronous) because reading the config file is unavoidably async.
213
+ */
214
+ static async syncEnvDeclaration(cwd) {
215
+ const rootTypesDir = path.join(cwd, '.testspectra', 'types');
216
+ if (!fs.existsSync(rootTypesDir)) {
217
+ fs.mkdirSync(rootTypesDir, { recursive: true });
218
+ }
219
+ let environmentVariables = {};
220
+ try {
221
+ const config = await ConfigLoader.loadConfig(cwd);
222
+ environmentVariables = config.executionConfig?.environmentVariables ?? {};
223
+ }
224
+ catch { }
225
+ fs.writeFileSync(path.join(rootTypesDir, 'env.d.ts'), this.generateEnvDeclaration(environmentVariables), 'utf-8');
226
+ }
191
227
  /**
192
228
  * Discovers all feature directories and shared library directories.
193
229
  * Returns a map of scope -> base directory
@@ -267,10 +303,11 @@ export class TypeGenerator {
267
303
  }
268
304
  return dirs;
269
305
  }
270
- static generateDeclarationsForScope(cwd, outputTypesDir, scopeDir, sharedDir) {
306
+ static generateDeclarationsForScope(cwd, outputTypesDir, scopeDir, sharedDir, rootTypesDir) {
271
307
  const poDirs = this.getPageObjectsDirsForScope(scopeDir, sharedDir);
272
308
  const actionsDirs = this.getEntityDirsForScope('actions', scopeDir, sharedDir);
273
309
  const stepsDirs = this.getEntityDirsForScope('steps', scopeDir, sharedDir);
310
+ const isComponentTesting = isComponentTestingProject(cwd);
274
311
  const platforms = ['web', 'android', 'ios', 'mobile', 'common'];
275
312
  const results = {
276
313
  web: '',
@@ -279,14 +316,39 @@ export class TypeGenerator {
279
316
  mobile: '',
280
317
  common: '',
281
318
  };
319
+ // `env.d.ts` always lives at the workspace root types dir (env vars come from a single
320
+ // `spectra.config.ts`, unlike per-scope fixtures/page-objects), so a shared/feature scope's
321
+ // own declarations reference it via a relative path back up to the root.
322
+ let envRefPath = './env.d.ts';
323
+ if (rootTypesDir && rootTypesDir !== outputTypesDir) {
324
+ envRefPath = path.relative(outputTypesDir, path.join(rootTypesDir, 'env.d.ts')).replace(/\\/g, '/');
325
+ if (!envRefPath.startsWith('.'))
326
+ envRefPath = `./${envRefPath}`;
327
+ }
282
328
  for (const platform of platforms) {
283
329
  const hierarchy = PLATFORM_HIERARCHY[platform];
284
330
  let content = `// Auto-generated ambient declarations for TestSpectra [${platform.toUpperCase()}]\n`;
285
331
  content += `// Managed automatically by TestSpectra Language Service Plugin.\n\n`;
286
- content += `/// <reference types="@wdio/globals/types" />\n`;
287
- content += `/// <reference types="@wdio/mocha-framework" />\n`;
332
+ // TestSpectra's Rust-native orchestrator worker (core/orchestrator/src/worker/bdd_runner.ts)
333
+ // registers its own `it`/`test`/lifecycle-hook globals directly — there is no WDIO or Mocha
334
+ // runtime involved at all (not just for component testing; this is true across every
335
+ // platform). `describe` is intentionally NOT declared here even though the runtime has a
336
+ // transparent no-op implementation of it — spec-schema-linter's no-describe-block rule
337
+ // forbids authoring it, so leaving it undeclared makes that a compile error too, not just a
338
+ // lint error.
339
+ content += `declare function it(title: string, fn: () => Promise<void> | void): void;\n`;
340
+ if (isComponentTesting) {
341
+ // Vitest's own `expect` global (test.globals: true in tools/react/vitest.config.ts) — the
342
+ // one thing component specs legitimately need beyond the Spectra.* DSL, for asserting
343
+ // plain closure/callback state (e.g. "was this onClick handler invoked") that has no DOM
344
+ // element to target. Reuses @testspectra/react's own re-exported `ExpectStatic` type
345
+ // rather than hand-duplicating Vitest's expect API surface. Not declared for E2E projects
346
+ // — the Rust orchestrator's BDD runtime has no `expect` global at all.
347
+ content += `declare const expect: import('@testspectra/react').ExpectStatic;\n`;
348
+ }
288
349
  content += `/// <reference types="@testspectra/matchers" />\n`;
289
- content += `/// <reference path="./fixtures.d.ts" />\n\n`;
350
+ content += `/// <reference path="./fixtures.d.ts" />\n`;
351
+ content += `/// <reference path="${envRefPath}" />\n\n`;
290
352
  // 1. Page Objects Global Declarations
291
353
  const declaredPOMs = new Set();
292
354
  for (const poDir of poDirs) {
@@ -423,7 +485,10 @@ export class TypeGenerator {
423
485
  }
424
486
  }
425
487
  content += `}\n`;
426
- content += `type TestSpectraActions = import('@testspectra/matchers').SpectraStatic & TestSpectraCustomActions;\n`;
488
+ // Reuses @testspectra/react's own exported `mount` type rather than hand-duplicating its
489
+ // signature here — stays in sync automatically if that signature ever changes.
490
+ const mountAugment = isComponentTesting ? ` & { mount: typeof import('@testspectra/react').mount }` : '';
491
+ content += `type TestSpectraActions = import('@testspectra/matchers').SpectraStatic & TestSpectraCustomActions${mountAugment};\n`;
427
492
  content += `declare const Spectra: TestSpectraActions;\n\n`;
428
493
  // 3. Built-in Steps Declaration
429
494
  content += `interface TestSpectraSteps {\n`;
@@ -543,11 +608,42 @@ export class TypeGenerator {
543
608
  content += `declare const Fixture: TestSpectraFixtures;\n`;
544
609
  return content;
545
610
  }
611
+ /**
612
+ * Generates the typed `Spectra.env` ambient declaration from `spectra.config.ts`'s
613
+ * `executionConfig.environmentVariables` — mirrors `generateFixturesDeclarationForScope`, but
614
+ * env vars come from a single project-level config rather than a scanned directory.
615
+ *
616
+ * Emits a bare global `interface SpectraEnv { readonly KEY: string; ... }`, which TypeScript
617
+ * interface-merges with the empty `SpectraEnv` shipped by `@testspectra/matchers` (the same
618
+ * mechanism `@types/node` uses for projects to augment `NodeJS.ProcessEnv`) — so `Spectra.env.KEY`
619
+ * resolves to `string`, never `string | undefined` like raw `process.env.KEY`.
620
+ */
621
+ static generateEnvDeclaration(environmentVariables) {
622
+ let content = `// Auto-generated ambient Spectra.env declarations for TestSpectra\n`;
623
+ content += `// Managed automatically by TestSpectra Language Service Plugin.\n\n`;
624
+ content += `interface SpectraEnv {\n`;
625
+ for (const key of Object.keys(environmentVariables)) {
626
+ content += ` readonly ${JSON.stringify(key)}: string;\n`;
627
+ }
628
+ content += `}\n`;
629
+ return content;
630
+ }
546
631
  static writeDeclarationFiles(cwd) {
547
632
  const rootTypesDir = path.join(cwd, '.testspectra', 'types');
548
633
  if (!fs.existsSync(rootTypesDir)) {
549
634
  fs.mkdirSync(rootTypesDir, { recursive: true });
550
635
  }
636
+ // env.d.ts always lives at the root, regardless of Nx scopes — a single spectra.config.ts's
637
+ // executionConfig.environmentVariables applies workspace-wide (see generateEnvDeclaration).
638
+ // Reading spectra.config.ts itself is unavoidably async (ESM dynamic import), which would ripple
639
+ // an async signature through every caller of this long-standing sync method — instead, this only
640
+ // guarantees env.d.ts *exists* (so the reference below never points at a missing file) and
641
+ // leaves it accurate as of the last real sync. `syncEnvDeclaration` (called at the actual
642
+ // execution entry points: run/watch/sync-types) is what keeps its content up to date.
643
+ const envDtsPath = path.join(rootTypesDir, 'env.d.ts');
644
+ if (!fs.existsSync(envDtsPath)) {
645
+ fs.writeFileSync(envDtsPath, this.generateEnvDeclaration({}), 'utf-8');
646
+ }
551
647
  const scopes = this.getEntityScopes(cwd);
552
648
  const sharedScope = scopes.find((s) => s.isShared);
553
649
  const featureScopes = scopes.filter((s) => !s.isShared);
@@ -561,7 +657,7 @@ export class TypeGenerator {
561
657
  if (!hasScopes || hasRootEntities) {
562
658
  const rootFixtures = this.generateFixturesDeclarationForScope(cwd, rootTypesDir, cwd);
563
659
  fs.writeFileSync(path.join(rootTypesDir, 'fixtures.d.ts'), rootFixtures, 'utf-8');
564
- const rootDeclarations = this.generateDeclarationsForScope(cwd, rootTypesDir, cwd);
660
+ const rootDeclarations = this.generateDeclarationsForScope(cwd, rootTypesDir, cwd, undefined, rootTypesDir);
565
661
  for (const [platform, content] of Object.entries(rootDeclarations)) {
566
662
  fs.writeFileSync(path.join(rootTypesDir, `${platform}.d.ts`), content, 'utf-8');
567
663
  }
@@ -587,7 +683,7 @@ export class TypeGenerator {
587
683
  fs.mkdirSync(sharedTypesDir, { recursive: true });
588
684
  const sharedFixtures = this.generateFixturesDeclarationForScope(cwd, sharedTypesDir, sharedScope.dir);
589
685
  fs.writeFileSync(path.join(sharedTypesDir, 'fixtures.d.ts'), sharedFixtures, 'utf-8');
590
- const sharedDeclarations = this.generateDeclarationsForScope(cwd, sharedTypesDir, sharedScope.dir);
686
+ const sharedDeclarations = this.generateDeclarationsForScope(cwd, sharedTypesDir, sharedScope.dir, undefined, rootTypesDir);
591
687
  for (const [platform, content] of Object.entries(sharedDeclarations)) {
592
688
  fs.writeFileSync(path.join(sharedTypesDir, `${platform}.d.ts`), content, 'utf-8');
593
689
  }
@@ -609,7 +705,7 @@ export class TypeGenerator {
609
705
  fs.mkdirSync(featureTypesDir, { recursive: true });
610
706
  const featureFixtures = this.generateFixturesDeclarationForScope(cwd, featureTypesDir, feature.dir, sharedScope?.dir);
611
707
  fs.writeFileSync(path.join(featureTypesDir, 'fixtures.d.ts'), featureFixtures, 'utf-8');
612
- const featureDeclarations = this.generateDeclarationsForScope(cwd, featureTypesDir, feature.dir, sharedScope?.dir);
708
+ const featureDeclarations = this.generateDeclarationsForScope(cwd, featureTypesDir, feature.dir, sharedScope?.dir, rootTypesDir);
613
709
  for (const [platform, content] of Object.entries(featureDeclarations)) {
614
710
  fs.writeFileSync(path.join(featureTypesDir, `${platform}.d.ts`), content, 'utf-8');
615
711
  }
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import { doctorCommand } from './commands/doctor.js';
6
6
  import { initCommand } from './commands/init.js';
7
7
  import { installCommand } from './commands/install.js';
8
8
  import { runCommand } from './commands/run.js';
9
+ import { testCommand } from './commands/test.js';
9
10
  import { updateCommand } from './commands/update.js';
10
11
  import { watchCommand } from './commands/watch.js';
11
12
  import { syncTypesCommand } from './commands/sync-types.js';
@@ -27,7 +28,7 @@ export function createCliProgram() {
27
28
  program
28
29
  .command('init')
29
30
  .description('Initialize testspectra.config.json and project directories')
30
- .option('-t, --template <template>', 'Project template: default, nx')
31
+ .option('-t, --template <template>', 'Project template: default, nx, react-component')
31
32
  .option('-f, --force', 'Overwrite existing configuration if present')
32
33
  .action(initCommand);
33
34
  program
@@ -167,6 +168,19 @@ Examples:
167
168
  .option('-w, --workdir <dir>', 'Custom app data / temp workdir')
168
169
  .option('-o, --output <path>', 'Custom test report JSON output path')
169
170
  .action(runCommand);
171
+ program
172
+ .command('test')
173
+ .description('Run React component tests via @testspectra/react (bundled Vitest browser mode)')
174
+ .option('-w, --cwd <dir>', 'Custom workspace directory')
175
+ .option('-s, --spec <path>', 'Spec file path (or substring filter) to execute')
176
+ .option('--headless', 'Run in headless mode (default)')
177
+ .option('--no-headless', 'Run in headed mode')
178
+ .option('--headed', 'Run the browser in visible GUI mode (alias for --no-headless)')
179
+ .option('--step-delay <ms>', 'Delay after each action/assertion in milliseconds (slow motion, for observing DOM transitions in --headed mode)')
180
+ .option('--delay <ms>', 'Alias for --step-delay')
181
+ .option('-c, --concurrency <number>', 'Run spec files sequentially (1) or in parallel (>1, default). Browser mode has no numeric N-worker sizing like `spectra run`.')
182
+ .option('-o, --output <path>', 'Write a Vitest JSON test report to this path')
183
+ .action(testCommand);
170
184
  return program;
171
185
  }
172
186
  export async function runCli(args = process.argv) {
@@ -0,0 +1,115 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
5
+ import { SpecLinter } from '../spec-linter.js';
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+ /**
9
+ * Covers the component-testing `.tsx` import exception (see
10
+ * docs/v2/features/component-testing/react/mount-convention.md §"Static Imports Are Allowed
11
+ * Here"): imports are allowed in `.test.tsx` files EXCEPT ones resolving into ambient-global-
12
+ * backed directories (page-objects/, support/steps/, fixtures/). Structural rules
13
+ * (single-it-required, no-describe-block) stay fully enforced for `.tsx` exactly as for `.ts`.
14
+ */
15
+ describe('Component Test (.tsx) Import Exception', () => {
16
+ const tempDir = path.join(__dirname, '__temp_tsx_imports__');
17
+ const specFrontmatter = `---
18
+ id: TC-0200
19
+ title: Sample component test
20
+ priority: High
21
+ caseType: Positive
22
+ status: automated
23
+ coverage:
24
+ web: automated
25
+ ---
26
+
27
+ # Sample component test
28
+
29
+ ## Test Steps
30
+ 1. Mount the component and assert it is visible.
31
+ `;
32
+ beforeEach(() => {
33
+ fs.mkdirSync(tempDir, { recursive: true });
34
+ fs.writeFileSync(path.join(tempDir, 'spec.md'), specFrontmatter);
35
+ });
36
+ afterEach(() => {
37
+ if (fs.existsSync(tempDir)) {
38
+ fs.rmSync(tempDir, { recursive: true, force: true });
39
+ }
40
+ });
41
+ it('does not flag no-manual-import for ordinary component/library imports in .test.tsx', () => {
42
+ fs.writeFileSync(path.join(tempDir, 'web.test.tsx'), `import { Button } from '../../src/components/Button/Button.js';
43
+ import React from 'react';
44
+
45
+ it('Sample component test', async () => {
46
+ await Spectra.mount(<Button label="Save" />);
47
+ });
48
+ `);
49
+ const { diagnostics } = SpecLinter.validateSpecFile(path.join(tempDir, 'spec.md'));
50
+ const importErrors = diagnostics.filter((d) => d.code === 'testspectra/no-manual-import');
51
+ expect(importErrors).toHaveLength(0);
52
+ });
53
+ it('still flags no-manual-import when a .test.tsx import resolves into page-objects/', () => {
54
+ fs.writeFileSync(path.join(tempDir, 'web.test.tsx'), `import ButtonComponent from '../../page-objects/ButtonComponent/web.js';
55
+
56
+ it('Sample component test', async () => {
57
+ await ButtonComponent.root.shouldBeVisible();
58
+ });
59
+ `);
60
+ const { diagnostics } = SpecLinter.validateSpecFile(path.join(tempDir, 'spec.md'));
61
+ const importErrors = diagnostics.filter((d) => d.code === 'testspectra/no-manual-import');
62
+ expect(importErrors).toHaveLength(1);
63
+ expect(importErrors[0].message).toContain('page-objects');
64
+ });
65
+ it('still flags no-manual-import when a .test.tsx import resolves into support/steps/', () => {
66
+ fs.writeFileSync(path.join(tempDir, 'web.test.tsx'), `import verifyButtonState from '../../support/steps/verifyButtonState/web.step.js';
67
+
68
+ it('Sample component test', async () => {
69
+ await verifyButtonState('Save', true);
70
+ });
71
+ `);
72
+ const { diagnostics } = SpecLinter.validateSpecFile(path.join(tempDir, 'spec.md'));
73
+ const importErrors = diagnostics.filter((d) => d.code === 'testspectra/no-manual-import');
74
+ expect(importErrors).toHaveLength(1);
75
+ });
76
+ it('still flags no-manual-import when a .test.tsx import resolves into fixtures/', () => {
77
+ fs.writeFileSync(path.join(tempDir, 'web.test.tsx'), `import users from '../../fixtures/users.json';
78
+
79
+ it('Sample component test', async () => {
80
+ expect(users).toBeDefined();
81
+ });
82
+ `);
83
+ const { diagnostics } = SpecLinter.validateSpecFile(path.join(tempDir, 'spec.md'));
84
+ const importErrors = diagnostics.filter((d) => d.code === 'testspectra/no-manual-import');
85
+ expect(importErrors).toHaveLength(1);
86
+ });
87
+ it('still enforces single-it-required and no-describe-block in .test.tsx files', () => {
88
+ fs.writeFileSync(path.join(tempDir, 'web.test.tsx'), `import { Button } from '../../src/components/Button/Button.js';
89
+
90
+ describe('Button', () => {
91
+ it('Sample component test', async () => {
92
+ await Spectra.mount(<Button label="Save" />);
93
+ });
94
+
95
+ it('Another test', async () => {
96
+ await Spectra.mount(<Button label="Cancel" />);
97
+ });
98
+ });
99
+ `);
100
+ const { diagnostics } = SpecLinter.validateSpecFile(path.join(tempDir, 'spec.md'));
101
+ expect(diagnostics.some((d) => d.code === 'testspectra/no-describe-block')).toBe(true);
102
+ expect(diagnostics.some((d) => d.code === 'testspectra/single-it-required')).toBe(true);
103
+ });
104
+ it('still forbids all imports (unchanged behavior) in plain .test.ts E2E specs', () => {
105
+ fs.writeFileSync(path.join(tempDir, 'web.test.ts'), `import { LoginPage } from '../../page-objects/LoginPage/web.js';
106
+
107
+ it('Sample component test', async () => {
108
+ await LoginPage.submitButton.click();
109
+ });
110
+ `);
111
+ const { diagnostics } = SpecLinter.validateSpecFile(path.join(tempDir, 'spec.md'));
112
+ const importErrors = diagnostics.filter((d) => d.code === 'testspectra/no-manual-import');
113
+ expect(importErrors).toHaveLength(1);
114
+ });
115
+ });
@@ -28,6 +28,7 @@ export interface ExtractedCodeSymbols {
28
28
  importStatements: Array<{
29
29
  line: number;
30
30
  column: number;
31
+ specifier: string;
31
32
  }>;
32
33
  }
33
34
  /**
@@ -50,11 +50,21 @@ export function extractSymbolsFromTestCode(code, filePath) {
50
50
  const importStatements = [];
51
51
  function visit(node) {
52
52
  // 1. Detect manual import statements (TS-LINT-006)
53
- if (ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node)) {
53
+ if (ts.isImportDeclaration(node)) {
54
54
  const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
55
+ const specifier = ts.isStringLiteral(node.moduleSpecifier) ? node.moduleSpecifier.text : '';
55
56
  importStatements.push({
56
57
  line: line + 1,
57
58
  column: character + 1,
59
+ specifier,
60
+ });
61
+ }
62
+ else if (ts.isImportEqualsDeclaration(node)) {
63
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
64
+ importStatements.push({
65
+ line: line + 1,
66
+ column: character + 1,
67
+ specifier: '',
58
68
  });
59
69
  }
60
70
  // 2. Detect it(...) / test(...) [forbidden] and describe(...) / suite(...) call expressions (TS-LINT-007, TS-LINT-008, TS-LINT-005)
@@ -11,11 +11,11 @@ export declare const CoverageSchema: z.ZodObject<{
11
11
  web: z.ZodOptional<z.ZodEnum<["automated", "manual", "unsupported"]>>;
12
12
  mobile: z.ZodOptional<z.ZodEnum<["automated", "manual", "unsupported"]>>;
13
13
  }, "strip", z.ZodTypeAny, {
14
- web?: "automated" | "manual" | "unsupported" | undefined;
15
14
  mobile?: "automated" | "manual" | "unsupported" | undefined;
16
- }, {
17
15
  web?: "automated" | "manual" | "unsupported" | undefined;
16
+ }, {
18
17
  mobile?: "automated" | "manual" | "unsupported" | undefined;
18
+ web?: "automated" | "manual" | "unsupported" | undefined;
19
19
  }>;
20
20
  export declare const SpecFrontmatterSchema: z.ZodObject<{
21
21
  id: z.ZodString;
@@ -27,33 +27,33 @@ export declare const SpecFrontmatterSchema: z.ZodObject<{
27
27
  web: z.ZodOptional<z.ZodEnum<["automated", "manual", "unsupported"]>>;
28
28
  mobile: z.ZodOptional<z.ZodEnum<["automated", "manual", "unsupported"]>>;
29
29
  }, "strip", z.ZodTypeAny, {
30
- web?: "automated" | "manual" | "unsupported" | undefined;
31
30
  mobile?: "automated" | "manual" | "unsupported" | undefined;
32
- }, {
33
31
  web?: "automated" | "manual" | "unsupported" | undefined;
32
+ }, {
34
33
  mobile?: "automated" | "manual" | "unsupported" | undefined;
34
+ web?: "automated" | "manual" | "unsupported" | undefined;
35
35
  }>>;
36
36
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
37
37
  }, "strip", z.ZodTypeAny, {
38
- priority: "Critical" | "High" | "Medium" | "Low";
39
- id: string;
38
+ status: "draft" | "ready-for-automation" | "automated" | "deprecated";
40
39
  title: string;
40
+ id: string;
41
+ priority: "Critical" | "High" | "Medium" | "Low";
41
42
  caseType: "Positive" | "Negative" | "Edge";
42
- status: "draft" | "ready-for-automation" | "automated" | "deprecated";
43
43
  coverage?: {
44
- web?: "automated" | "manual" | "unsupported" | undefined;
45
44
  mobile?: "automated" | "manual" | "unsupported" | undefined;
45
+ web?: "automated" | "manual" | "unsupported" | undefined;
46
46
  } | undefined;
47
47
  tags?: string[] | undefined;
48
48
  }, {
49
- priority: "Critical" | "High" | "Medium" | "Low";
50
- id: string;
49
+ status: "draft" | "ready-for-automation" | "automated" | "deprecated";
51
50
  title: string;
51
+ id: string;
52
+ priority: "Critical" | "High" | "Medium" | "Low";
52
53
  caseType: "Positive" | "Negative" | "Edge";
53
- status: "draft" | "ready-for-automation" | "automated" | "deprecated";
54
54
  coverage?: {
55
- web?: "automated" | "manual" | "unsupported" | undefined;
56
55
  mobile?: "automated" | "manual" | "unsupported" | undefined;
56
+ web?: "automated" | "manual" | "unsupported" | undefined;
57
57
  } | undefined;
58
58
  tags?: string[] | undefined;
59
59
  }>;