@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.
- package/package.json +1 -1
- package/skills/nocobase-app-development/SKILL.md +23 -7
- package/skills/nocobase-app-development/references/app-structure.md +4 -0
- package/skills/nocobase-app-development/references/frontend/references/page.md +6 -0
- package/skills/nocobase-app-development/references/frontend/references/testing.md +11 -59
- package/skills/nocobase-app-development/references/frontend/references/ui-library.md +28 -1
- package/skills/nocobase-app-development/references/lifecycle-parameters.md +10 -4
- package/skills/nocobase-app-development/references/lifecycle-ui.md +122 -0
- package/skills/nocobase-app-development/references/lifecycle.md +9 -5
- package/skills/nocobase-app-development/references/system-administration.md +32 -0
- package/skills/nocobase-app-development/references/system-settings.md +4 -4
- package/skills/nocobase-app-development/references/testing/cli/command.md +157 -0
- package/skills/nocobase-app-development/references/testing/cli/files.md +258 -0
- package/skills/nocobase-app-development/references/testing/client/page.md +301 -0
- package/skills/nocobase-app-development/references/testing/database/migration.md +50 -0
- package/skills/nocobase-app-development/references/testing/database/repository.md +160 -0
- package/skills/nocobase-app-development/references/testing/playwright/login.md +147 -0
- package/skills/nocobase-app-development/references/testing/server/routes.md +178 -0
- package/skills/nocobase-app-development/references/testing.md +53 -0
- package/skills/nocobase-app-upgrade/SKILL.md +2 -0
- package/skills/nocobase-app-upgrade/references/edge-cases.md +12 -0
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
# Client example: submit, retry and prevent duplicate requests
|
|
2
|
+
|
|
3
|
+
Use `renderWithApp()` for a component that consumes NocoBase client services. It starts a client application, provides a memory router, the real API client, strict translations and a test toaster. `answerApi()` supplies the HTTP responses, so no backend or database is required for this example.
|
|
4
|
+
|
|
5
|
+
This complete example assumes a NocoBase 3 application with its normal React, TypeScript and test dependencies installed. It uses `@nocobase/app-testing/client`, `@nocobase/app-client`, `@nocobase/i18n`, `@nocobase/dev-config`, Vitest, jsdom, Testing Library, user-event and jest-dom.
|
|
6
|
+
|
|
7
|
+
## Configure client tests
|
|
8
|
+
|
|
9
|
+
Create `vitest.client.config.ts` at the application root. The shared React preset provides jsdom, JSX transformation, jest-dom assertions and DOM cleanup after each test. An application that already has a client Vitest project can use that project instead. Discover both `.test.ts` and `.test.tsx` files; retain Vitest's default file parallelism for client-only suites, while keeping cases that share one DOM sequential.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createReactVitestConfig } from '@nocobase/dev-config/vitest/react';
|
|
13
|
+
|
|
14
|
+
export default createReactVitestConfig({
|
|
15
|
+
cacheDir: './storage/tests/vite-client',
|
|
16
|
+
test: {
|
|
17
|
+
include: ['tests/client/**/*.test.{ts,tsx}'],
|
|
18
|
+
passWithNoTests: false,
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Prepare the component and translations
|
|
24
|
+
|
|
25
|
+
Create `client/components/create-note-button.tsx`. The component submits a title, disables its button while the request is pending, and reports success or an error. In feature work, import the real component instead of reproducing its implementation inside a test.
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
import { useApiClient, useToaster } from '@nocobase/app-client';
|
|
29
|
+
import { useTranslation } from '@nocobase/i18n/client';
|
|
30
|
+
import { useState, type ReactElement } from 'react';
|
|
31
|
+
|
|
32
|
+
export function CreateNoteButton({
|
|
33
|
+
title,
|
|
34
|
+
}: {
|
|
35
|
+
readonly title: string;
|
|
36
|
+
}): ReactElement {
|
|
37
|
+
const api = useApiClient();
|
|
38
|
+
const toaster = useToaster();
|
|
39
|
+
const { t } = useTranslation();
|
|
40
|
+
const [pending, setPending] = useState(false);
|
|
41
|
+
const [failed, setFailed] = useState(false);
|
|
42
|
+
|
|
43
|
+
function createNote(): void {
|
|
44
|
+
setPending(true);
|
|
45
|
+
setFailed(false);
|
|
46
|
+
api
|
|
47
|
+
.request({
|
|
48
|
+
path: 'testingNotes',
|
|
49
|
+
method: 'POST',
|
|
50
|
+
json: { title },
|
|
51
|
+
})
|
|
52
|
+
.then(() => {
|
|
53
|
+
toaster.show({ type: 'success', title: t('testingNotes.created') });
|
|
54
|
+
})
|
|
55
|
+
.catch(() => {
|
|
56
|
+
setFailed(true);
|
|
57
|
+
})
|
|
58
|
+
.finally(() => {
|
|
59
|
+
setPending(false);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return (
|
|
64
|
+
<>
|
|
65
|
+
<button type='button' disabled={pending} onClick={createNote}>
|
|
66
|
+
{t('testingNotes.create')}
|
|
67
|
+
</button>
|
|
68
|
+
{failed ? <p role='alert'>{t('testingNotes.failed')}</p> : null}
|
|
69
|
+
</>
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Add the following translations. If these files already exist, merge the `testingNotes` keys into their default exports and preserve the other keys.
|
|
75
|
+
|
|
76
|
+
`client/locales/en-US.ts`:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
export default {
|
|
80
|
+
testingNotes: {
|
|
81
|
+
create: 'Create note',
|
|
82
|
+
created: 'Note created',
|
|
83
|
+
failed: 'Could not create the note. Try again.',
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`client/locales/zh-CN.ts`:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
export default {
|
|
92
|
+
testingNotes: {
|
|
93
|
+
create: '创建笔记',
|
|
94
|
+
created: '笔记已创建',
|
|
95
|
+
failed: '无法创建笔记,请重试。',
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`client/locales/index.ts`:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import type { LocaleLoaders } from '@nocobase/i18n';
|
|
104
|
+
|
|
105
|
+
const locales: LocaleLoaders = {
|
|
106
|
+
'en-US': () => import('./en-US.js'),
|
|
107
|
+
'zh-CN': () => import('./zh-CN.js'),
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
export default locales;
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The sample API contract is `POST /api/testingNotes` with `{ title }`, returning status `201` with `{ data: { id, title } }`. The test supplies this response; adding a real backend route is separate feature work.
|
|
114
|
+
|
|
115
|
+
## Test submission, failure, retry and pending state
|
|
116
|
+
|
|
117
|
+
Create `tests/client/create-note.test.tsx`:
|
|
118
|
+
|
|
119
|
+
```tsx
|
|
120
|
+
import '@testing-library/jest-dom/vitest';
|
|
121
|
+
import {
|
|
122
|
+
answerApi,
|
|
123
|
+
renderWithApp,
|
|
124
|
+
type ApiCall,
|
|
125
|
+
} from '@nocobase/app-testing/client';
|
|
126
|
+
import { act, screen, waitFor } from '@testing-library/react';
|
|
127
|
+
import userEvent from '@testing-library/user-event';
|
|
128
|
+
import { expect, it, vi } from 'vitest';
|
|
129
|
+
import { CreateNoteButton } from '../../client/components/create-note-button.js';
|
|
130
|
+
import enUS from '../../client/locales/en-US.js';
|
|
131
|
+
import locales from '../../client/locales/index.js';
|
|
132
|
+
import zhCN from '../../client/locales/zh-CN.js';
|
|
133
|
+
import packageMetadata from '../../package.json' with { type: 'json' };
|
|
134
|
+
|
|
135
|
+
const title = 'Review invoice';
|
|
136
|
+
const createdNote = { data: { id: 'note-1', title } };
|
|
137
|
+
const expectedCall: ApiCall = {
|
|
138
|
+
method: 'POST',
|
|
139
|
+
path: 'testingNotes',
|
|
140
|
+
json: { title },
|
|
141
|
+
};
|
|
142
|
+
const translations = {
|
|
143
|
+
'en-US': enUS.testingNotes,
|
|
144
|
+
'zh-CN': zhCN.testingNotes,
|
|
145
|
+
};
|
|
146
|
+
const localeCases = ['en-US', 'zh-CN'] as const;
|
|
147
|
+
|
|
148
|
+
async function renderCreateNote(
|
|
149
|
+
respond: () => Response | Promise<Response>,
|
|
150
|
+
locale: keyof typeof translations = 'en-US',
|
|
151
|
+
) {
|
|
152
|
+
const user = userEvent.setup();
|
|
153
|
+
const handler = vi.fn((call: ApiCall) => {
|
|
154
|
+
if (call.method !== 'POST' || call.path !== 'testingNotes') {
|
|
155
|
+
return new Response(null, { status: 404 });
|
|
156
|
+
}
|
|
157
|
+
return respond();
|
|
158
|
+
});
|
|
159
|
+
const view = await renderWithApp(<CreateNoteButton title={title} />, {
|
|
160
|
+
namespace: packageMetadata.name,
|
|
161
|
+
namespaces: { [packageMetadata.name]: locales },
|
|
162
|
+
locale,
|
|
163
|
+
fetch: answerApi(handler),
|
|
164
|
+
});
|
|
165
|
+
const copy = translations[locale];
|
|
166
|
+
const button = screen.getByRole('button', { name: copy.create });
|
|
167
|
+
return { user, handler, view, copy, button };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
it.each(localeCases)('submits a note and confirms it in %s', async (locale) => {
|
|
171
|
+
const { user, handler, view, copy, button } = await renderCreateNote(
|
|
172
|
+
() => Response.json(createdNote, { status: 201 }),
|
|
173
|
+
locale,
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
await user.click(button);
|
|
177
|
+
|
|
178
|
+
await waitFor(() => {
|
|
179
|
+
expect(view.toasts()).toMatchObject([
|
|
180
|
+
{ type: 'success', title: copy.created },
|
|
181
|
+
]);
|
|
182
|
+
expect(button).toBeEnabled();
|
|
183
|
+
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
|
184
|
+
});
|
|
185
|
+
expect(handler.mock.calls).toEqual([[expectedCall]]);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it.each(localeCases)(
|
|
189
|
+
'shows a failure and retries successfully in %s',
|
|
190
|
+
async (locale) => {
|
|
191
|
+
const retry = Promise.withResolvers<Response>();
|
|
192
|
+
const respond = vi
|
|
193
|
+
.fn<() => Response | Promise<Response>>()
|
|
194
|
+
.mockReturnValueOnce(new Response(null, { status: 500 }))
|
|
195
|
+
.mockReturnValue(retry.promise);
|
|
196
|
+
const { user, handler, view, copy, button } = await renderCreateNote(
|
|
197
|
+
respond,
|
|
198
|
+
locale,
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
await user.click(button);
|
|
203
|
+
|
|
204
|
+
await waitFor(() => {
|
|
205
|
+
expect(screen.getByRole('alert')).toHaveTextContent(copy.failed);
|
|
206
|
+
expect(button).toBeEnabled();
|
|
207
|
+
expect(view.toasts()).toEqual([]);
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
await user.click(button);
|
|
211
|
+
|
|
212
|
+
expect(button).toBeDisabled();
|
|
213
|
+
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
|
214
|
+
expect(view.toasts()).toEqual([]);
|
|
215
|
+
} finally {
|
|
216
|
+
await act(async () => {
|
|
217
|
+
retry.resolve(Response.json(createdNote, { status: 201 }));
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
await waitFor(() => {
|
|
222
|
+
expect(view.toasts()).toMatchObject([
|
|
223
|
+
{ type: 'success', title: copy.created },
|
|
224
|
+
]);
|
|
225
|
+
expect(button).toBeEnabled();
|
|
226
|
+
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
|
227
|
+
});
|
|
228
|
+
expect(handler.mock.calls).toEqual([[expectedCall], [expectedCall]]);
|
|
229
|
+
},
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
it('prevents a duplicate request while submitting', async () => {
|
|
233
|
+
const response = Promise.withResolvers<Response>();
|
|
234
|
+
const { user, handler, view, copy, button } = await renderCreateNote(
|
|
235
|
+
() => response.promise,
|
|
236
|
+
);
|
|
237
|
+
|
|
238
|
+
try {
|
|
239
|
+
await user.click(button);
|
|
240
|
+
|
|
241
|
+
await waitFor(() => {
|
|
242
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
243
|
+
});
|
|
244
|
+
expect(button).toBeDisabled();
|
|
245
|
+
expect(view.toasts()).toEqual([]);
|
|
246
|
+
|
|
247
|
+
await user.click(button);
|
|
248
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
249
|
+
} finally {
|
|
250
|
+
await act(async () => {
|
|
251
|
+
response.resolve(Response.json(createdNote, { status: 201 }));
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
await waitFor(() => {
|
|
256
|
+
expect(view.toasts()).toMatchObject([
|
|
257
|
+
{ type: 'success', title: copy.created },
|
|
258
|
+
]);
|
|
259
|
+
expect(button).toBeEnabled();
|
|
260
|
+
});
|
|
261
|
+
expect(handler.mock.calls).toEqual([[expectedCall]]);
|
|
262
|
+
});
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
The two success cases check the complete request and confirmation in English and Chinese. Two retry cases check the translated failure message, then hold the retry pending to verify that the old error clears immediately, the button disables and no success appears before the response. The final case verifies that a second click during submission cannot send another request.
|
|
266
|
+
|
|
267
|
+
`renderCreateNote()` is a local setup helper for this component. Each call creates its own user-event session, request spy and client application; assertions and response timing stay in the test. Keep the helper local until another test actually needs the same setup.
|
|
268
|
+
|
|
269
|
+
The request spy records every call before matching the method and path. Unexpected endpoints return `404`; `handler.mock.calls` checks the exact request history, including payloads and duplicates. Keep those assertions outside `answerApi()`: it converts a thrown assertion into an HTTP 500, which an error-state test could mistake for its intended failure.
|
|
270
|
+
|
|
271
|
+
Wait for the final toast and enabled button together, because the success callback and `finally` complete separate parts of the interaction. Perform clicks outside `waitFor()`, whose callback may run repeatedly. Use `Promise.withResolvers<Response>()` to control pending requests without timers, and resolve them inside `act()` in `finally` so even a failing assertion releases the request before fixture cleanup.
|
|
272
|
+
|
|
273
|
+
The application namespace and locale loaders are real. Missing translation keys fail the test. For a plugin-owned page, pass its registration in `plugins` and its package name in `namespace`; for a page that needs other services, include the registrations it actually consumes. `renderWithApp()` shuts down its client application when each test finishes.
|
|
274
|
+
|
|
275
|
+
## Adapt the harness to the page
|
|
276
|
+
|
|
277
|
+
| The page needs | Supply or assert |
|
|
278
|
+
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
|
279
|
+
| Application-owned translations | `namespace: packageMetadata.name` and `namespaces: { [packageMetadata.name]: locales }` |
|
|
280
|
+
| A plugin's services or translations | Its actual registration in `plugins` and the owning namespace; include the dependencies its provider needs |
|
|
281
|
+
| A starting client URL | `route`; it sets the memory router's initial entry |
|
|
282
|
+
| Several API operations | Branch in `answerApi()` on `method`, `path`, `query` or `json`; return an explicit error response for unexpected calls |
|
|
283
|
+
| A domain error | Return a `Response` with the real API's status and error envelope so the component exercises its error handling |
|
|
284
|
+
| A service double | Register it in `services` before startup and omit the plugin that would register the same token |
|
|
285
|
+
| An existing in-process test server | Supply `server: testApp` and, after real sign-in, `cookie: session.cookie`; close the server with its owning fixture |
|
|
286
|
+
|
|
287
|
+
`answerApi()` receives paths below `/api/`, such as `testingNotes`, while server request helpers accept `/users`. An object returned by the handler is sent as JSON with status `200`; return a `Response` to select another status, including `201` or `500`. A thrown handler error becomes a `500` response. The test's `vi.fn()` observes the HTTP boundary; keep `useApiClient()`, `useTranslation()` and `useToaster()` real.
|
|
288
|
+
|
|
289
|
+
Call `renderWithApp()` inside the test rather than `beforeAll`: it registers shutdown with Vitest's `onTestFinished`. The shared React preset unmounts the DOM after each test. Do not disable strict translations to hide a missing key, and do not replace the installed router configuration with a second router wrapper. Client tests cover component interactions and requests; permissions and persistence need the real [server fixture](../server/routes.md).
|
|
290
|
+
|
|
291
|
+
## Run and check
|
|
292
|
+
|
|
293
|
+
Run from the application root:
|
|
294
|
+
|
|
295
|
+
```bash
|
|
296
|
+
pnpm exec vitest run --config vitest.client.config.ts --reporter=verbose
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
Expect one test file and five passing cases. These checks cover client interaction, API request construction and translations. Use the [server example](../server/routes.md) for permissions and persistence.
|
|
300
|
+
|
|
301
|
+
Return to [testing and verification](../../testing.md).
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# Database example: apply, roll back and reapply a migration
|
|
2
|
+
|
|
3
|
+
Use `describeMigration()` to verify the schema a migration produces and what its rollback leaves behind. It executes the migration through the migrator on a real test database, including metadata checks, instead of calling `up()` with a mocked builder.
|
|
4
|
+
|
|
5
|
+
## Prerequisites
|
|
6
|
+
|
|
7
|
+
Create `vitest.database.config.ts`, the fixture migration and `tests/helpers/testing-notes.ts` from [the repository example](repository.md). This example targets that exact migration name. For application work, use the actual migration name and sources, including any earlier migrations it depends on. Do not modify a migration already merged into the target branch; write and test a new correction migration.
|
|
8
|
+
|
|
9
|
+
## Test the schema
|
|
10
|
+
|
|
11
|
+
Create `tests/database/notes-migration.test.ts`:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { describeMigration } from '@nocobase/app-testing/server';
|
|
15
|
+
import { noteMigrations } from '../helpers/testing-notes.js';
|
|
16
|
+
|
|
17
|
+
describeMigration('202610180001_testing_create_notes', {
|
|
18
|
+
sources: noteMigrations,
|
|
19
|
+
up: async ({ expectCollection }) => {
|
|
20
|
+
await expectCollection('testingNotes').toHaveField('id', {
|
|
21
|
+
type: 'string',
|
|
22
|
+
nullable: false,
|
|
23
|
+
});
|
|
24
|
+
await expectCollection('testingNotes').toHaveField('title', {
|
|
25
|
+
type: 'string',
|
|
26
|
+
nullable: false,
|
|
27
|
+
});
|
|
28
|
+
await expectCollection('testingNotes').toHaveIndex(['title'], {
|
|
29
|
+
unique: true,
|
|
30
|
+
});
|
|
31
|
+
},
|
|
32
|
+
down: async ({ expectCollection }) => {
|
|
33
|
+
await expectCollection('testingNotes').not.toExist();
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The helper owns and destroys its database, including when a callback fails. It applies earlier migrations, applies this migration and calls `up`, rolls it back and calls `down`, then reapplies it and calls `up` again. It also checks agreement between collection metadata and physical tables and that rollback restores the previous schema. Keep `up` assertions valid on both passes.
|
|
39
|
+
|
|
40
|
+
`expectCollection()` uses logical collection and field names, so the checks do not depend on a database's generated index names, case folding or schema-inspection SQL. For a data migration, use the helper's `before` callback to insert pre-migration records and assert the transformed values in `up`. A table alteration should leave its original table intact after `down`, so assert the removed field or index rather than copying the table-removal assertion above.
|
|
41
|
+
|
|
42
|
+
## Run and check
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pnpm exec vitest run --config vitest.database.config.ts tests/database/notes-migration.test.ts
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Expect one passing test; within that test the helper applies the migration, rolls it back and applies it again, with the assertions at each stage. A no-op `down` would leave the collection behind and fail. For a deliberately irreversible migration, `reversible: false` verifies application only; it is not a way to bypass a broken rollback.
|
|
49
|
+
|
|
50
|
+
Return to [testing and verification](../../testing.md).
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# Database example: records, constraints, transactions and isolation
|
|
2
|
+
|
|
3
|
+
Use `createDatabaseTest()` from `@nocobase/app-testing/server` for repository behavior that needs a real database but no application services or HTTP routes. It supplies a database manager, a default connection and schema assertions, runs the supplied migrations, and cleans up the test databases. This example covers create/read/update/delete, a unique constraint, transaction rollback and isolation between cases.
|
|
4
|
+
|
|
5
|
+
## Configure database tests
|
|
6
|
+
|
|
7
|
+
Use an existing NocoBase 3 application with `@nocobase/app-testing`, `@nocobase/db`, a compatible test dialect driver, `@nocobase/dev-config` and Vitest installed. The default dialect is SQLite. Create `vitest.database.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-database',
|
|
14
|
+
test: {
|
|
15
|
+
include: ['tests/database/**/*.test.ts'],
|
|
16
|
+
fileParallelism: false,
|
|
17
|
+
passWithNoTests: false,
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The dedicated config selects Node and only these tests. If the application already has a Node test project, add the files to its discovery instead; preserve its existing setup and aliases. Run database suites sequentially.
|
|
23
|
+
|
|
24
|
+
## Prepare a small fixture
|
|
25
|
+
|
|
26
|
+
This example owns a synthetic `testingNotes` collection. Keep its migration under `tests/fixtures/` so it is not installed into the running application. When testing a real application collection, use its actual migration sources and prerequisite migrations instead of copying production migrations into the fixture. Application plugin providers and seeds are not discovered automatically by `createDatabaseTest()`; pass the migration and seed sources the test needs, or use `createAppTest()` when composition is what you need to verify.
|
|
27
|
+
|
|
28
|
+
Create `tests/fixtures/testing-notes/migrations/202610180001_testing_create_notes.ts`:
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { defineMigration, type MigrationDefinition } from '@nocobase/db';
|
|
32
|
+
|
|
33
|
+
const migration: MigrationDefinition = defineMigration({
|
|
34
|
+
name: '202610180001_testing_create_notes',
|
|
35
|
+
async up({ builder }) {
|
|
36
|
+
await builder.createCollection('testingNotes', (collection) => {
|
|
37
|
+
collection.string('id', { primaryKey: true, nullable: false });
|
|
38
|
+
collection.string('title', { nullable: false });
|
|
39
|
+
collection.unique(['title'], { mode: 'index' });
|
|
40
|
+
});
|
|
41
|
+
},
|
|
42
|
+
async down({ builder }) {
|
|
43
|
+
await builder.dropCollection('testingNotes');
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
export default migration;
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Create `tests/helpers/testing-notes.ts`. The application identity comes from its manifest, and paths resolve from this file rather than the shell's working directory:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { fileURLToPath } from 'node:url';
|
|
54
|
+
import type { MigrationSource } from '@nocobase/db';
|
|
55
|
+
import packageMetadata from '../../package.json' with { type: 'json' };
|
|
56
|
+
|
|
57
|
+
export const noteMigrations: readonly MigrationSource[] = [
|
|
58
|
+
{
|
|
59
|
+
packageName: packageMetadata.name,
|
|
60
|
+
directory: fileURLToPath(
|
|
61
|
+
new URL('../fixtures/testing-notes/migrations/', import.meta.url),
|
|
62
|
+
),
|
|
63
|
+
},
|
|
64
|
+
];
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Test the records
|
|
68
|
+
|
|
69
|
+
Create `tests/database/notes.test.ts`:
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import { expect } from 'vitest';
|
|
73
|
+
import { createDatabaseTest } from '@nocobase/app-testing/server';
|
|
74
|
+
import { noteMigrations } from '../helpers/testing-notes.js';
|
|
75
|
+
|
|
76
|
+
const test = createDatabaseTest({ migrations: noteMigrations });
|
|
77
|
+
|
|
78
|
+
test('creates, reads, updates and deletes a note', async ({ connection }) => {
|
|
79
|
+
const notes = connection.repository('testingNotes');
|
|
80
|
+
|
|
81
|
+
await notes.createOne({
|
|
82
|
+
values: { id: 'note-1', title: 'Draft' },
|
|
83
|
+
});
|
|
84
|
+
await notes.updateOne({
|
|
85
|
+
filter: { id: 'note-1' },
|
|
86
|
+
values: { title: 'Reviewed' },
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
await expect(
|
|
90
|
+
notes.findOne({ filter: { id: 'note-1' } }),
|
|
91
|
+
).resolves.toMatchObject({ id: 'note-1', title: 'Reviewed' });
|
|
92
|
+
await expect(notes.count()).resolves.toBe(1);
|
|
93
|
+
|
|
94
|
+
await notes.deleteOne({ filter: { id: 'note-1' } });
|
|
95
|
+
await expect(notes.count()).resolves.toBe(0);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('rejects duplicate titles', async ({ connection }) => {
|
|
99
|
+
const notes = connection.repository('testingNotes');
|
|
100
|
+
|
|
101
|
+
await notes.createOne({
|
|
102
|
+
values: { id: 'note-1', title: 'Review invoice' },
|
|
103
|
+
});
|
|
104
|
+
await expect(
|
|
105
|
+
notes.createOne({
|
|
106
|
+
values: { id: 'note-2', title: 'Review invoice' },
|
|
107
|
+
}),
|
|
108
|
+
).rejects.toThrow();
|
|
109
|
+
|
|
110
|
+
await expect(notes.count()).resolves.toBe(1);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test('rolls back every write when the operation fails', async ({
|
|
114
|
+
database,
|
|
115
|
+
connection,
|
|
116
|
+
}) => {
|
|
117
|
+
await expect(
|
|
118
|
+
database.transaction(async (transaction) => {
|
|
119
|
+
const notes = transaction.repository('testingNotes');
|
|
120
|
+
await notes.createOne({
|
|
121
|
+
values: { id: 'note-1', title: 'First note' },
|
|
122
|
+
});
|
|
123
|
+
await notes.createOne({
|
|
124
|
+
values: { id: 'note-2', title: 'Second note' },
|
|
125
|
+
});
|
|
126
|
+
throw new Error('Operation cancelled');
|
|
127
|
+
}),
|
|
128
|
+
).rejects.toThrow('Operation cancelled');
|
|
129
|
+
|
|
130
|
+
await expect(connection.repository('testingNotes').count()).resolves.toBe(0);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('starts another case with an empty collection', async ({ connection }) => {
|
|
134
|
+
await expect(connection.repository('testingNotes').count()).resolves.toBe(0);
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Use the repository from the transaction callback for every write that must roll back; the ordinary connection's repository is not part of that transaction. Assert the data after failure rather than checking driver-specific error text. The unique-constraint test uses different IDs so the rejected write exercises the title index rather than the primary key.
|
|
139
|
+
|
|
140
|
+
The fixture defaults to `isolation: 'schema'`: it resets the databases and reapplies migrations and seeds before each case. The final case therefore starts empty regardless of test order. `isolation: 'none'` shares state for the file and is appropriate only for cases deliberately designed that way. For multiple connections, pass all names in `connections`; access a non-default one with `database.connection(name)`.
|
|
141
|
+
|
|
142
|
+
## Run and check
|
|
143
|
+
|
|
144
|
+
From the application root:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
pnpm exec vitest run --config vitest.database.config.ts tests/database/notes.test.ts
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Expect four passing cases. Run `pnpm exec vitest run --config vitest.database.config.ts` after adding the [migration test](migration.md) to run both files: four repository cases and one migration case.
|
|
151
|
+
|
|
152
|
+
For an installed PostgreSQL driver with its test server configured, select it without changing the test code:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
NOCOBASE_TEST_DB_DIALECT=postgres pnpm exec vitest run --config vitest.database.config.ts
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
The PostgreSQL test driver reads `POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_USER`, `POSTGRES_PASSWORD` and `POSTGRES_DATABASE` (or their `PG*` equivalents). Use a test database server where the provisioner can create and drop isolated schemas. The test never imports a dialect driver or hardcodes an in-memory database. A successful SQLite run does not verify other dialects.
|
|
159
|
+
|
|
160
|
+
Continue with [migration assertions](migration.md), or the [server example](../server/routes.md) for application registration and HTTP permissions. Return to [testing and verification](../../testing.md).
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# Playwright example: sign in once and reuse the session
|
|
2
|
+
|
|
3
|
+
Use Playwright for a flow that needs the actual browser, server and session cookie. There is no `@nocobase/app-testing/playwright` export. `createAppTest()` handles requests in process; it does not provide the HTTP address a browser needs.
|
|
4
|
+
|
|
5
|
+
## Prerequisites
|
|
6
|
+
|
|
7
|
+
Start a dedicated test application with its own database and storage. Use the full application entry URL printed as `Local:` by `pnpm dev`, including the deployment base path. For ordinary full-stack development this is the Hono server entry, not Vite's internal port. The example assumes the template's `/login` form in English, an enabled test account, and a home page with a level-one heading. Adapt accessible names to the application's actual localized UI.
|
|
8
|
+
|
|
9
|
+
The official templates include `@playwright/test` and `playwright.config.ts`. If Chromium is not installed, run `pnpm exec playwright install chromium`. In an application without Playwright, follow [frontend test setup](../../frontend/references/testing.md#where-tests-go) first. Keep `tests/playwright/**` excluded from Vitest and included in `tsconfig.node.json`.
|
|
10
|
+
|
|
11
|
+
Set `APP_URL`, `E2E_USERNAME` and `E2E_PASSWORD` in the shell or the CI secret environment. For example, `APP_URL=http://127.0.0.1:13000/main/` is valid only when it matches this test application's actual ready URL. No account values belong in committed test files. The template ignores `storage/`; preserve that exclusion because the saved browser state contains the session cookie.
|
|
12
|
+
|
|
13
|
+
## Resolve paths without dropping the deployment prefix
|
|
14
|
+
|
|
15
|
+
Create `tests/playwright/environment.ts`:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { fileURLToPath } from 'node:url';
|
|
19
|
+
|
|
20
|
+
const entry = process.env.APP_URL;
|
|
21
|
+
if (!entry)
|
|
22
|
+
throw new Error('Set APP_URL to the running test application entry.');
|
|
23
|
+
|
|
24
|
+
export const appUrl = new URL(`${entry.replace(/\/+$/, '')}/`);
|
|
25
|
+
export const authFile = fileURLToPath(
|
|
26
|
+
new URL('../../storage/e2e/auth.json', import.meta.url),
|
|
27
|
+
);
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Use relative URL paths below: `new URL('login', appUrl)` preserves `/main/`, whereas `new URL('/login', appUrl)` discards it.
|
|
31
|
+
|
|
32
|
+
## Sign in during global setup
|
|
33
|
+
|
|
34
|
+
Create `tests/playwright/global-setup.ts`:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { mkdir } from 'node:fs/promises';
|
|
38
|
+
import { dirname } from 'node:path';
|
|
39
|
+
import { chromium, expect } from '@playwright/test';
|
|
40
|
+
import { appUrl, authFile } from './environment.js';
|
|
41
|
+
|
|
42
|
+
export default async function globalSetup(): Promise<void> {
|
|
43
|
+
const username = process.env.E2E_USERNAME;
|
|
44
|
+
const password = process.env.E2E_PASSWORD;
|
|
45
|
+
if (!username || !password) {
|
|
46
|
+
throw new Error('Set E2E_USERNAME and E2E_PASSWORD for the test account.');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const browser = await chromium.launch();
|
|
50
|
+
try {
|
|
51
|
+
const context = await browser.newContext({ locale: 'en-US' });
|
|
52
|
+
const page = await context.newPage();
|
|
53
|
+
await page.goto(new URL('login', appUrl).href);
|
|
54
|
+
await page.getByLabel('Username or email').fill(username);
|
|
55
|
+
await page.getByLabel('Password', { exact: true }).fill(password);
|
|
56
|
+
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
|
|
57
|
+
await page.waitForURL(
|
|
58
|
+
(url) => !url.pathname.replace(/\/$/, '').endsWith('/login'),
|
|
59
|
+
);
|
|
60
|
+
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
|
|
61
|
+
|
|
62
|
+
const session = await page.request.get(
|
|
63
|
+
new URL('api/auth/get-session', appUrl).href,
|
|
64
|
+
);
|
|
65
|
+
expect(session.status()).toBe(200);
|
|
66
|
+
await expect(session.json()).resolves.toMatchObject({
|
|
67
|
+
user: { id: expect.any(String) },
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
await mkdir(dirname(authFile), { recursive: true });
|
|
71
|
+
await context.storageState({ path: authFile });
|
|
72
|
+
} finally {
|
|
73
|
+
await browser.close();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Global setup creates fresh state for each run. A failed sign-in fails setup instead of silently skipping the suite or saving an anonymous session.
|
|
79
|
+
|
|
80
|
+
## Load the saved state
|
|
81
|
+
|
|
82
|
+
For the template's single-browser configuration, add `globalSetup` and `use.storageState`, preserving any other application-specific settings:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
// playwright.config.ts
|
|
86
|
+
import { defineConfig } from '@playwright/test';
|
|
87
|
+
import { authFile } from './tests/playwright/environment.js';
|
|
88
|
+
|
|
89
|
+
export default defineConfig({
|
|
90
|
+
testDir: './tests/playwright',
|
|
91
|
+
testMatch: '**/*.test.ts',
|
|
92
|
+
globalSetup: './tests/playwright/global-setup.ts',
|
|
93
|
+
timeout: 120_000,
|
|
94
|
+
workers: 1,
|
|
95
|
+
reporter: 'list',
|
|
96
|
+
use: {
|
|
97
|
+
browserName: 'chromium',
|
|
98
|
+
locale: 'en-US',
|
|
99
|
+
storageState: authFile,
|
|
100
|
+
trace: 'off',
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Create `tests/playwright/session.test.ts`:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import { expect, test } from '@playwright/test';
|
|
109
|
+
import { appUrl } from './environment.js';
|
|
110
|
+
|
|
111
|
+
test('opens the home page and retains the session after a reload', async ({
|
|
112
|
+
page,
|
|
113
|
+
}) => {
|
|
114
|
+
const pageErrors: string[] = [];
|
|
115
|
+
page.on('pageerror', (error) => pageErrors.push(error.message));
|
|
116
|
+
|
|
117
|
+
await page.goto(appUrl.href);
|
|
118
|
+
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
|
|
119
|
+
await expect(page.getByLabel('Password', { exact: true })).toHaveCount(0);
|
|
120
|
+
await page.reload();
|
|
121
|
+
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
|
|
122
|
+
|
|
123
|
+
const response = await page.request.get(
|
|
124
|
+
new URL('api/auth/get-session', appUrl).href,
|
|
125
|
+
);
|
|
126
|
+
expect(response.status()).toBe(200);
|
|
127
|
+
await expect(response.json()).resolves.toMatchObject({
|
|
128
|
+
user: { id: expect.any(String) },
|
|
129
|
+
});
|
|
130
|
+
expect(pageErrors).toEqual([]);
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`page.request` shares the browser context's cookies. The session assertion distinguishes a real signed-in session from an anonymous `200` response with a null body. Each test gets its own browser context initialized from the saved state, but the account and backend data remain shared. Tests that change preferences, permissions or records need separate users or test-owned data with cleanup.
|
|
135
|
+
|
|
136
|
+
## Run and check
|
|
137
|
+
|
|
138
|
+
With the application already running and the three environment variables set:
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
pnpm exec playwright test tests/playwright/session.test.ts
|
|
142
|
+
pnpm exec tsc -p tsconfig.node.json --noEmit
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Expect one browser test, preceded by a successful setup login. The flow checks rendering, session reuse after reload, an authenticated API response and browser page errors. It does not verify a business operation or a permission matrix. Add those flows only when they need a real browser; use [client tests](../client/page.md) for loading, error and translation combinations.
|
|
146
|
+
|
|
147
|
+
Return to [testing and verification](../../testing.md).
|