@nocobase/app-skills 0.1.0-beta.37 → 0.1.0-beta.39

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 (21) hide show
  1. package/package.json +1 -1
  2. package/skills/nocobase-app-development/SKILL.md +23 -7
  3. package/skills/nocobase-app-development/references/app-structure.md +4 -0
  4. package/skills/nocobase-app-development/references/frontend/references/page.md +6 -0
  5. package/skills/nocobase-app-development/references/frontend/references/testing.md +11 -59
  6. package/skills/nocobase-app-development/references/frontend/references/ui-library.md +28 -1
  7. package/skills/nocobase-app-development/references/lifecycle-parameters.md +10 -4
  8. package/skills/nocobase-app-development/references/lifecycle-ui.md +122 -0
  9. package/skills/nocobase-app-development/references/lifecycle.md +9 -5
  10. package/skills/nocobase-app-development/references/system-administration.md +32 -0
  11. package/skills/nocobase-app-development/references/system-settings.md +4 -4
  12. package/skills/nocobase-app-development/references/testing/cli/command.md +157 -0
  13. package/skills/nocobase-app-development/references/testing/cli/files.md +258 -0
  14. package/skills/nocobase-app-development/references/testing/client/page.md +301 -0
  15. package/skills/nocobase-app-development/references/testing/database/migration.md +50 -0
  16. package/skills/nocobase-app-development/references/testing/database/repository.md +160 -0
  17. package/skills/nocobase-app-development/references/testing/playwright/login.md +147 -0
  18. package/skills/nocobase-app-development/references/testing/server/routes.md +178 -0
  19. package/skills/nocobase-app-development/references/testing.md +53 -0
  20. package/skills/nocobase-app-upgrade/SKILL.md +2 -0
  21. package/skills/nocobase-app-upgrade/references/edge-cases.md +12 -0
@@ -6,7 +6,7 @@ A usable application includes administration for the capabilities it uses. Do no
6
6
 
7
7
  A newly created Default application shows Home only and does not register a System settings group or its routes. The template includes reusable application-owned Users and Roles and permissions page modules, ready to enable as the application develops. Examples is already a built application and registers them.
8
8
 
9
- As business capabilities are developed, automatically supply core user and permission administration and any management surfaces those capabilities need. If the core settings routes are still absent, import `systemSettingsRoutes` from `./pages/settings/routes.js` in `client/routes.ts` and append it once to the exported route contribution array: `const routes: readonly AppClientRouteContribution[] = [appRoutes, systemSettingsRoutes]`. Reuse an existing registration instead of duplicating it. Do not make the user ask for user or permission settings separately, and do not grant access to ordinary users as a side effect. Existing applications that predate these modules should install or build equivalent real management pages as part of the current development task when needed. Preserve already enabled pages and their server authorization on every iteration. Do not use a first-build flag, a one-time setup stage, or the number of development rounds as the trigger. Reuse UsersClient and AuthorizationClient; the plugins own accounts, role scopes, grants, protected sets and their invariants. Keep personal account and appearance controls in the existing account/header surfaces.
9
+ As business capabilities are developed, automatically supply core user and permission administration and any management surfaces those capabilities need. If the core settings routes are still absent, import `systemSettingsRoutes` from `./pages/settings/routes.js` in `client/routes.ts` and append it once to the exported route contribution array: `const routes: readonly AppClientRouteContribution[] = [appRoutes, systemSettingsRoutes]`. Reuse an existing registration instead of duplicating it. If System management already exists, register the contribution's child routes with `parent: 'systemManagement'` (using the existing group's actual name), instead of registering a second settings group so Users, Roles and permissions, Workflow management and other administration entries appear together while retaining their URLs and permission ids. Do not make the user ask for user or permission settings separately, and do not grant access to ordinary users as a side effect. Existing applications that predate these modules should install or build equivalent real management pages as part of the current development task when needed. Preserve already enabled pages and their server authorization on every iteration. Do not use a first-build flag, a one-time setup stage, or the number of development rounds as the trigger. Reuse UsersClient and AuthorizationClient; the plugins own accounts, role scopes, grants, protected sets and their invariants. Keep personal account and appearance controls in the existing account/header surfaces.
10
10
 
11
11
  ## Reconcile administration on every iteration
12
12
 
@@ -47,7 +47,7 @@ Reuse the actual Host, Hub or deployment workflow for database connections, serv
47
47
 
48
48
  ## Workflow integration
49
49
 
50
- For an application-owned lifecycle, register the real descriptions explicitly in one application provider. Expose an authenticated, authorized catalogue and definition detail endpoint, using schema allowlists and the standard API envelope. Never serialize the runtime, closures, credentials or execution contexts. Build one process-management directory under the application's Settings navigation group using the standard `DataTable`, even when only one process is registered. Never redirect the directory straight into that one definition. List the actual registered processes with stable identifiers, localized names, types and useful runtime-derived metadata; provide search, bounded pagination and supported sorting. Each process opens its own URL-addressable detail with `Definition` and `Execution records` sections. Keep node configuration on the corresponding state or transition, and link each execution to its real business record, progress, decisions and diagnostic history as supported by that runtime. Preserve list filters and pagination when returning from detail or an overlay. Later development adds new registered processes to this same directory instead of creating a separate menu for each one. Use `@nocobase/lifecycle-diagram`, which installs the standard `@nocobase/flow-diagram` canvas, rather than a bespoke bare React Flow view. Source-defined structure is read-only; proactively declared business parameters are edited through their authorized service as described below.
50
+ For an application-owned lifecycle, register the real descriptions explicitly in one application provider. Expose an authenticated, authorized catalogue and definition detail endpoint, using schema allowlists and the standard API envelope. Never serialize the runtime, closures, credentials or execution contexts. Build one workflow-management entry under the application's existing System management or Settings navigation group using the `@nocobase/workflow-management` block, even when only one process is registered. Keep `Definitions` and `Executions` as tabs within this page, as described in [Lifecycle UI](lifecycle-ui.md); use the standard `DataTable` for its list content. Never redirect the directory straight into that one definition. List the actual registered processes with stable identifiers, localized names, types and useful runtime-derived metadata; provide search, bounded pagination and supported sorting. Each process opens its own URL-addressable definition detail and links to executions filtered to that process within the same management page. Keep node configuration on the corresponding state or transition, and link each execution to its real business record, progress, decisions and diagnostic history as supported by that runtime. Preserve list filters and pagination when returning from detail or an overlay. Later development adds new registered processes to this same directory instead of creating a separate menu for each one. Use `@nocobase/lifecycle-diagram`, which installs the standard `@nocobase/flow-diagram` canvas, rather than a bespoke bare React Flow view. Source-defined structure is read-only; proactively declared business parameters are edited through their authorized service as described below.
51
51
 
52
52
  Catalogue entries must explicitly bind their runtime definition, record collection, read permissions and execution adapter. Validate the process identifier on definition, parameter and execution endpoints; reject unknown identifiers and never fall back to another process's records. Filter by the selected process and enforce its business scope before counting or paging. Do not fabricate enable/disable, publish, edit-topology or delete controls when the installed runtime does not support them.
53
53
 
@@ -72,7 +72,7 @@ Whenever building or changing business behavior, inspect its conditions, limits,
72
72
 
73
73
  For lifecycles, use the installed runtime's `parameterConfiguration`, store, service and editor contracts; read [configurable lifecycle parameters](lifecycle-parameters.md). For policy outside a lifecycle, use the application's existing configuration service or implement the application-owned contract in [business administration recipes](business-administration.md#business-parameters); lifecycle-only APIs are not a generic settings service. Declare defaults, schema, validation, bindings, authorization and snapshot/live behavior together. The server's actual route, reviewer resolver or business decision must consume the saved values. An editable form over a hard-coded condition does not satisfy this requirement. Reuse authoritative organization and account data; never guess an approver or substitute demonstration people. A single-assignee workflow must keep its decision semantics unless multi-candidate decisions are implemented and verified.
74
74
 
75
- For lifecycles, expose bound fields automatically from the standard definition diagram. States and transitions with real bindings expose an explicit localized Configure control on the corresponding element, opening the shared editor or authoritative relationship settings; configuration read without update permission remains read-only. Preserve ordinary inspection for unbound elements. The same stored configuration powers any central settings page and diagram entry. Do not ask whether to add the diagram or parameter entry when delivering a process application, unless the user explicitly requests API-only work or omits the interface.
75
+ For lifecycles, deliver the workflow management entry and visible parameter forms as [Lifecycle UI](lifecycle-ui.md) describes. Provide diagram-bound Configure controls for declared, authorized bindings by default through `LifecycleDiagram.configuration`, opening the same editor or authoritative relationship settings. Configuration read without update permission remains read-only, and unbound elements retain ordinary inspection. The same stored configuration powers the inline form and any diagram entry. Respect explicit API-only scope and omitted interfaces.
76
76
 
77
77
  For approval policy, default to snapshot semantics for a formal submission unless the business requirement calls for live changes. Explain when a saved change takes effect; existing submitted snapshots, assigned candidates and historical facts remain fixed. Technical constants, authorization guards, workflow topology, credentials, payment identities and code-owned trigger scheduling are not inferred as editable business parameters. A timing field is editable only when the runtime explicitly supports its scheduling semantics. Preserve valid existing values and revisions when adding new bindings; handle already submitted records through the lifecycle's documented compatibility policy.
78
78
 
@@ -80,4 +80,4 @@ For approval policy, default to snapshot semantics for a formal submission unles
80
80
 
81
81
  Check every applicable row above, not just the capability named by the user. Include a concise delivery map in the development report: capability, working entry, owning persistence/API, permission, execution consumer, and observed evidence or explicit limitation. Read [acceptance scenarios](business-administration.md#acceptance-scenarios) for blind-prompt and iteration checks. This is development evidence, not implementation detail to display to application users.
82
82
 
83
- Before finishing, map each used capability to its working management entry, route, real API, server-side permission and verification evidence. Group entries under the existing Settings route; hide an empty group after permission filtering. Repeated additions reconcile missing entries only: no duplicate menus, role seeds or configuration. Preserve existing stable route ids and unrelated administrator grants. Verify an authorized administrator, a user without management access, direct API denial, loading/empty/error states, write failure, deep links, Chinese/English, dark/light and narrow layouts. Keep execution data current through the existing realtime mechanism or a working Refresh action. For inferred threshold and reviewer parameters, save a different valid configuration and prove that a new eligible business execution uses it; also verify invalid values, an unauthorized update, snapshot preservation and repeated iterations without duplicate fields or bindings.
83
+ Before finishing, map each used capability to its working management entry, route, real API, server-side permission and verification evidence. Group entries under the existing System management or Settings navigation section, with workflow definitions and executions as page tabs rather than sibling menus; hide an empty group after permission filtering. Repeated additions reconcile missing entries only: no duplicate menus, role seeds or configuration. Preserve existing stable route ids and unrelated administrator grants. Verify an authorized administrator, a user without management access, direct API denial, loading/empty/error states, write failure, deep links, Chinese/English, dark/light and narrow layouts. Keep execution data current through the existing realtime mechanism or a working Refresh action. For inferred threshold and reviewer parameters, save a different valid configuration and prove that a new eligible business execution uses it; also verify invalid values, an unauthorized update, snapshot preservation and repeated iterations without duplicate fields or bindings.
@@ -0,0 +1,157 @@
1
+ # CLI example: run a command on an isolated application database
2
+
3
+ Use `bindTestAppCommand()` when a command opens the application. It binds the command to the configuration from `createTestAppConfig()`, so the command reads the test's databases. `runAppCommand()` captures the result, exit code and JSON output without spawning the CLI runner.
4
+
5
+ For a complete command that works with files and needs no application database, start with [file output, dry runs and failures](files.md).
6
+
7
+ ## Prerequisites
8
+
9
+ Create the migration and `noteMigrations` helper from [the database example](../database/repository.md). Use an application with `server/app.ts`, `server/runtime.ts` and `database/main/migrations/`, as the templates provide. Adjust the application migration directory below if its configured sources differ. The example provisions `main`; include every application-owned connection if there are more, as described in [the server example](../server/routes.md).
10
+
11
+ ## Configure CLI tests
12
+
13
+ Create `vitest.cli.config.ts` at the application root, or reuse the identical config from [the file-command example](files.md):
14
+
15
+ ```ts
16
+ import { createNodeVitestConfig } from '@nocobase/dev-config/vitest/node';
17
+
18
+ export default createNodeVitestConfig({
19
+ cacheDir: './storage/tests/vite-cli',
20
+ test: {
21
+ include: ['tests/cli/**/*.test.ts'],
22
+ fileParallelism: false,
23
+ passWithNoTests: false,
24
+ },
25
+ });
26
+ ```
27
+
28
+ Run this suite after any server or database suite has finished. The command creates a real application, including its providers and background services; `runAppCommand()` also temporarily captures process-wide output.
29
+
30
+ ## A small command to exercise
31
+
32
+ Create `tests/fixtures/count-notes-command.ts`. This fixture demonstrates a command without registering a new production CLI command. To test an existing command, import its real class from `cli/commands/` instead.
33
+
34
+ ```ts
35
+ import { AppCommand } from '@nocobase/app-cli';
36
+
37
+ export default class CountNotes extends AppCommand {
38
+ static override summary = 'Count the test notes.';
39
+
40
+ public async run(): Promise<{ count: number }> {
41
+ await this.parse(CountNotes);
42
+ const { databaseManagerToken } = await import('@nocobase/db');
43
+ return this.withApp(async ({ app }) => {
44
+ await app.start();
45
+ const database = app.container.resolve(databaseManagerToken);
46
+ const count = await database
47
+ .connection()
48
+ .repository('testingNotes')
49
+ .count();
50
+ return { count };
51
+ });
52
+ }
53
+ }
54
+ ```
55
+
56
+ `withApp()` closes the application after the callback, even if it fails. `app.start()` is needed here to initialize the application's services; it also starts registered jobs and schedules, so keep the application's test configuration appropriate for that work. Load the database runtime inside `run()` to keep command discovery cheap.
57
+
58
+ ## Prepare data and assert the JSON contract
59
+
60
+ Create `tests/cli/count-notes.test.ts`:
61
+
62
+ ```ts
63
+ import path from 'node:path';
64
+ import { fileURLToPath } from 'node:url';
65
+ import {
66
+ bindTestAppCommand,
67
+ createTestAppConfig,
68
+ runAppCommand,
69
+ } from '@nocobase/app-testing/cli';
70
+ import { expect, it, vi } from 'vitest';
71
+ import CountNotes from '../fixtures/count-notes-command.js';
72
+ import { noteMigrations } from '../helpers/testing-notes.js';
73
+ import packageMetadata from '../../package.json' with { type: 'json' };
74
+
75
+ const rootDir = fileURLToPath(new URL('../../', import.meta.url));
76
+
77
+ it.each([0, 2])('counts %i prepared records', async (count) => {
78
+ const config = await createTestAppConfig({
79
+ connections: ['main'],
80
+ config: {
81
+ database: {
82
+ connections: {
83
+ main: {
84
+ migrations: {
85
+ autoRun: true,
86
+ sources: [
87
+ {
88
+ packageName: packageMetadata.name,
89
+ directory: path.join(rootDir, 'database/main/migrations'),
90
+ },
91
+ ...noteMigrations,
92
+ ],
93
+ },
94
+ },
95
+ },
96
+ },
97
+ app: { publicOrigin: 'http://localhost' },
98
+ auth: {
99
+ secret: 'test-auth-secret-at-least-32-characters',
100
+ trustedOrigins: ['http://localhost'],
101
+ },
102
+ },
103
+ });
104
+ try {
105
+ vi.stubEnv('APP_STORAGE_DIR', path.join(config.directory, 'storage'));
106
+ const database = await config.testDatabases.open({
107
+ migrations: noteMigrations,
108
+ });
109
+ try {
110
+ for (let index = 0; index < count; index += 1) {
111
+ await database.connection.repository('testingNotes').createOne({
112
+ values: { id: `note-${index}`, title: `Note ${index}` },
113
+ });
114
+ }
115
+ } finally {
116
+ await database.destroy();
117
+ }
118
+
119
+ const run = await runAppCommand(
120
+ bindTestAppCommand(CountNotes, {
121
+ rootDir,
122
+ config,
123
+ id: 'app:notes:count',
124
+ }),
125
+ ['--json'],
126
+ );
127
+
128
+ expect(run.error).toBeUndefined();
129
+ expect(run.exitCode ?? 0).toBe(0);
130
+ expect(run.json()).toMatchObject({
131
+ ok: true,
132
+ command: 'app notes count',
133
+ status: 'success',
134
+ result: { count },
135
+ });
136
+ } finally {
137
+ vi.unstubAllEnvs();
138
+ await config.dispose();
139
+ }
140
+ });
141
+ ```
142
+
143
+ The test's preparation step and the command's startup must both know the fixture migration. `config.database.connections.main.migrations.sources` includes the application's own directory and `noteMigrations`; registered plugin migrations are added by the application. Listing only the fixture sources would omit the application's own migrations. Omitting the fixture sources would leave an applied migration in history that startup cannot find and cause it to fail. These overrides change migration discovery, not the provisioned connection's location.
144
+
145
+ `config.testDatabases.open()` resets and opens the provisioned databases before preparing the row. The returned handle does not own those databases, so `database.destroy()` closes the preparation connections while leaving the row for the command. `config.dispose()` is the owner cleanup: it drops the databases after the command has closed its application. Do not open the preparation handle again after running the command to inspect its writes; opening it resets the schema.
146
+
147
+ The storage override keeps application logs and background-worker state under the same temporary directory. Restore it in `finally`. Run these command cases sequentially: environment stubs and `runAppCommand()`'s stream capture are process-wide. A successful `runAppCommand()` has `exitCode: undefined`, which means zero; normalize it when asserting.
148
+
149
+ ## Run and check
150
+
151
+ ```bash
152
+ pnpm exec vitest run --config vitest.cli.config.ts tests/cli/count-notes.test.ts
153
+ ```
154
+
155
+ Expect two passing cases: an empty collection returns `result.count: 0`, and two prepared records return `result.count: 2`. Each case owns a separate configuration and databases. This proves the command reads the isolated database and obeys the JSON output contract. For a command with invalid-input or domain-error branches, also assert a nonzero exit and its documented `error.code`; a success case alone does not cover them. Commands that only manipulate files can use `bindAppCommand()` without provisioning a database, as [command authoring](../../commands.md#test) describes.
156
+
157
+ Return to [testing and verification](../../testing.md).
@@ -0,0 +1,258 @@
1
+ # CLI example: file output, dry runs and failures
2
+
3
+ Use `bindAppCommand()` and `runAppCommand()` from `@nocobase/app-testing/cli` to test an application command's argument parsing, returned data, text or JSON output, exit codes and file effects. This example writes a note to a new JSON file and needs no server or database. It assumes an existing NocoBase 3 application with `@nocobase/app-cli`, `@oclif/core`, `@nocobase/app-testing`, `@nocobase/dev-config` and Vitest installed at compatible versions.
4
+
5
+ ## Configure the tests
6
+
7
+ Create `vitest.cli.config.ts` at the application root:
8
+
9
+ ```ts
10
+ import { createNodeVitestConfig } from '@nocobase/dev-config/vitest/node';
11
+
12
+ export default createNodeVitestConfig({
13
+ cacheDir: './storage/tests/vite-cli',
14
+ test: {
15
+ include: ['tests/cli/**/*.test.ts'],
16
+ fileParallelism: false,
17
+ passWithNoTests: false,
18
+ },
19
+ });
20
+ ```
21
+
22
+ Keep these tests sequential. `runAppCommand()` temporarily captures process-wide output and restores the streams and exit code after each command; do not use `it.concurrent()` or run captured commands concurrently with `Promise.all()`.
23
+
24
+ ## Write the command
25
+
26
+ Create `cli/commands/notes/create.ts`. Its location registers it as `app notes create`; the command returns plain data and lets `AppCommand` print the JSON envelope. The `wx` write flag prevents overwriting an existing file.
27
+
28
+ ```ts
29
+ import { writeFile } from 'node:fs/promises';
30
+ import { AppCommand, CommandError, appPath } from '@nocobase/app-cli';
31
+ import { Flags } from '@oclif/core';
32
+
33
+ export interface CreateNoteResult {
34
+ readonly file: string;
35
+ readonly title: string;
36
+ readonly written: boolean;
37
+ }
38
+
39
+ export default class CreateNote extends AppCommand {
40
+ static override summary = 'Write a note to a new JSON file.';
41
+ static override examples = [
42
+ '<%= config.bin %> <%= command.id %> --title "Review invoice" --dry-run --json',
43
+ ];
44
+ static override flags = {
45
+ title: Flags.string({
46
+ required: true,
47
+ description: 'The note title.',
48
+ }),
49
+ output: appPath({
50
+ default: 'note.json',
51
+ description: 'The new file to write.',
52
+ }),
53
+ 'dry-run': Flags.boolean({
54
+ default: false,
55
+ description: 'Preview the result without writing a file.',
56
+ }),
57
+ };
58
+
59
+ public async run(): Promise<CreateNoteResult> {
60
+ const { flags } = await this.parse(CreateNote);
61
+ const title = flags.title.trim();
62
+ const file = flags.output;
63
+
64
+ if (!title) {
65
+ throw new CommandError('The title must not be blank.', {
66
+ code: 'INVALID_TITLE',
67
+ exit: 2,
68
+ });
69
+ }
70
+
71
+ if (flags['dry-run']) {
72
+ this.setStatus('success-noop');
73
+ this.log(`Would create ${file}.`);
74
+ return { file, title, written: false };
75
+ }
76
+
77
+ try {
78
+ await writeFile(file, `${JSON.stringify({ title }, null, 2)}\n`, {
79
+ encoding: 'utf8',
80
+ flag: 'wx',
81
+ });
82
+ } catch (error) {
83
+ if (
84
+ error instanceof Error &&
85
+ 'code' in error &&
86
+ error.code === 'EEXIST'
87
+ ) {
88
+ throw new CommandError('The output file already exists.', {
89
+ code: 'NOTE_EXISTS',
90
+ details: { file },
91
+ suggestions: ['Choose a different --output path.'],
92
+ });
93
+ }
94
+ throw error;
95
+ }
96
+
97
+ this.log(`Created ${file}.`);
98
+ return { file, title, written: true };
99
+ }
100
+ }
101
+ ```
102
+
103
+ `appPath()` resolves the default `note.json` from the application root. An explicit `--output` path resolves from the caller's current directory. Its parent directory must already exist. A dry run reports the planned file and title without attempting to write or checking whether the target already exists.
104
+
105
+ ## Test the command
106
+
107
+ Create `tests/cli/create-note.test.ts`. Every test receives its own temporary application root and removes it afterwards. The tests import the real command class.
108
+
109
+ ```ts
110
+ import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
111
+ import os from 'node:os';
112
+ import path from 'node:path';
113
+ import { bindAppCommand, runAppCommand } from '@nocobase/app-testing/cli';
114
+ import { afterEach, beforeEach, expect, it } from 'vitest';
115
+ import CreateNote from '../../cli/commands/notes/create.js';
116
+
117
+ let rootDir: string;
118
+ let Command: typeof CreateNote;
119
+
120
+ beforeEach(async () => {
121
+ rootDir = await mkdtemp(path.join(os.tmpdir(), 'notes-cli-test-'));
122
+ Command = bindAppCommand(CreateNote, {
123
+ rootDir,
124
+ id: 'app:notes:create',
125
+ });
126
+ });
127
+
128
+ afterEach(async () => {
129
+ await rm(rootDir, { recursive: true, force: true });
130
+ });
131
+
132
+ it('writes the note and returns one JSON document', async () => {
133
+ const file = path.join(rootDir, 'note.json');
134
+ const run = await runAppCommand(Command, [
135
+ '--title',
136
+ ' Review invoice ',
137
+ '--json',
138
+ ]);
139
+
140
+ expect(run.error).toBeUndefined();
141
+ expect(run.exitCode ?? 0).toBe(0);
142
+ expect(run.json()).toEqual({
143
+ schemaVersion: 1,
144
+ ok: true,
145
+ command: 'app notes create',
146
+ status: 'success',
147
+ result: { file, title: 'Review invoice', written: true },
148
+ warnings: [],
149
+ });
150
+ expect(await readFile(file, 'utf8')).toBe(
151
+ JSON.stringify({ title: 'Review invoice' }, null, 2) + '\n',
152
+ );
153
+ });
154
+
155
+ it('prints a readable result and honors --output', async () => {
156
+ const file = path.join(rootDir, 'custom-note.json');
157
+ const run = await runAppCommand(Command, [
158
+ '--title',
159
+ 'Review invoice',
160
+ '--output',
161
+ file,
162
+ ]);
163
+
164
+ expect(run.error).toBeUndefined();
165
+ expect(run.exitCode ?? 0).toBe(0);
166
+ expect(run.stdout).toBe(`Created ${file}.\n`);
167
+ expect(run.result).toEqual({ file, title: 'Review invoice', written: true });
168
+ expect(await readFile(file, 'utf8')).toContain('Review invoice');
169
+ expect(await readdir(rootDir)).toEqual(['custom-note.json']);
170
+ });
171
+
172
+ it('previews the result without writing a file', async () => {
173
+ const file = path.join(rootDir, 'note.json');
174
+ const run = await runAppCommand(Command, [
175
+ '--title',
176
+ 'Review invoice',
177
+ '--dry-run',
178
+ '--json',
179
+ ]);
180
+
181
+ expect(run.error).toBeUndefined();
182
+ expect(run.exitCode ?? 0).toBe(0);
183
+ expect(run.json()).toMatchObject({
184
+ ok: true,
185
+ status: 'success-noop',
186
+ result: { file, title: 'Review invoice', written: false },
187
+ });
188
+ expect(await readdir(rootDir)).toEqual([]);
189
+ });
190
+
191
+ it('refuses to overwrite an existing file', async () => {
192
+ const file = path.join(rootDir, 'note.json');
193
+ const original = JSON.stringify({ title: 'Keep this note' });
194
+ await writeFile(file, original);
195
+
196
+ const run = await runAppCommand(Command, [
197
+ '--title',
198
+ 'Replacement',
199
+ '--json',
200
+ ]);
201
+
202
+ expect(run.error).toBeUndefined();
203
+ expect(run.exitCode).toBe(1);
204
+ expect(run.json()).toMatchObject({
205
+ ok: false,
206
+ status: 'failure',
207
+ error: {
208
+ code: 'NOTE_EXISTS',
209
+ details: { file },
210
+ suggestions: [{ message: 'Choose a different --output path.' }],
211
+ },
212
+ });
213
+ expect(await readFile(file, 'utf8')).toBe(original);
214
+ });
215
+
216
+ it.each([
217
+ { name: 'missing title', args: [], code: 'INVALID_USAGE' },
218
+ { name: 'blank title', args: ['--title', ' '], code: 'INVALID_TITLE' },
219
+ ])('rejects $name without writing a file', async ({ args, code }) => {
220
+ const run = await runAppCommand(Command, [...args, '--json']);
221
+
222
+ expect(run.exitCode).toBe(2);
223
+ expect(run.json()).toMatchObject({
224
+ ok: false,
225
+ status: 'failure',
226
+ error: { code },
227
+ });
228
+ expect(await readdir(rootDir)).toEqual([]);
229
+ });
230
+ ```
231
+
232
+ These six cases check the written content and JSON envelope, text output with an explicit destination, a dry run with no file effects, preservation of an existing file, missing required input and a blank title. `run.json()` parses all of stdout as one JSON value, so extra text on stdout makes the JSON check fail.
233
+
234
+ With `--json`, a handled `CommandError` becomes the failure document and `run.error` can be `undefined`; assert `run.exitCode` and `run.json().error.code`. For a successful run, `exitCode: undefined` means zero. Without `--json`, `run.error` holds the error that the outer CLI runner would render. These tests exercise the command class; command discovery and deployment packaging are separate checks.
235
+
236
+ ## Choose a CLI fixture
237
+
238
+ Use `bindAppCommand()` for commands whose inputs and effects are files, flags or returned data. Its `rootDir` selects the test application root and `id` uses the runner's colon-separated command name. The helper does not create that directory, so the test creates it first. `runAppCommand()` exercises the command's parsing, lifecycle and output contract without spawning the outer runner.
239
+
240
+ If the command uses `withApp()` and needs real application services or records, use `bindTestAppCommand()` with `createTestAppConfig()`. Bind before running, close preparation database handles before the command starts, and dispose the configuration after the command finishes. The [database-backed example](command.md) shows the complete setup and both empty and populated results.
241
+
242
+ ## Run and check
243
+
244
+ From the application root:
245
+
246
+ ```bash
247
+ pnpm exec vitest run --config vitest.cli.config.ts --reporter=verbose
248
+ ```
249
+
250
+ Expect one test file and six passing cases. To inspect the command through the CLI, start with its preview:
251
+
252
+ ```bash
253
+ pnpm nocobase app notes create --title "Review invoice" --dry-run --json
254
+ ```
255
+
256
+ For commands that open the application and read or write its database, use `createTestAppConfig()` with `bindTestAppCommand()` as shown in [the database-backed command example](command.md).
257
+
258
+ Return to [testing and verification](../../testing.md).