Some checks failed
App Prod-Parity E2E Dispatch / dispatch (push) Failing after 10s
CD Storybook UI / build (push) Failing after 3m25s
CD Storybook UI / dispatch (push) Has been skipped
CD deploy main / website-changed-files (push) Successful in 18m8s
CI Agent Skills / changed-files-check (push) Successful in 18m9s
CI Create App E2E minimal / changed-files-check (push) Successful in 24s
CI Create App / changed-files-check (push) Successful in 26s
CI Docs / changed-files-check (push) Successful in 26s
CI Emails / changed-files-check (push) Successful in 28s
CI Example App Hello World / changed-files-check (push) Successful in 23s
CI Front / changed-files-check (push) Has been skipped
CI Example App Postcard / changed-files-check (push) Successful in 27s
CI UI / changed-files-check (push) Has been skipped
CI Utils Test / changed-files-check (push) Successful in 45s
CI Twenty Apps / discover (push) Successful in 1m3s
CD deploy main / deploy-main (push) Failing after 3s
CI Agent Skills / agent-skills-validate (push) Has been skipped
CI Create App / create-app-test (lint) (push) Has been skipped
CI Emails / emails-test (push) Has been skipped
CI Front / front-task (lingui:compile) (push) Has been skipped
CI Front / front-task (lint) (push) Has been skipped
CI Example App Postcard / example-app-postcard (push) Has been skipped
CI UI / ui-task (lint) (push) Has been skipped
CI UI / ui-task (pack-size) (push) Has been skipped
CI UI / ui-task (size) (push) Has been skipped
CI UI / ui-task (test) (push) Has been skipped
CI UI / ui-task (typecheck) (push) Has been skipped
CI Utils Test / utils-test (push) Has been skipped
CI Twenty Apps / ${{ matrix.app.name }} (push) Has been skipped
CI Emails / ci-emails-status-check (push) Successful in 2s
CI Example App Hello World / ci-example-app-hello-world-status-check (push) Successful in 2s
CI Example App Postcard / ci-example-app-postcard-status-check (push) Successful in 3s
CI UI / ui-sb-test (push) Has been skipped
CI Utils Test / ci-utils-test-status-check (push) Successful in 2s
CI Twenty Apps / ci-twenty-apps-status-check (push) Successful in 2s
CI UI / ci-ui-status-check (push) Successful in 2s
CI Desktop / desktop (push) Failing after 1m8s
Push docs to Crowdin / Push documentation to Crowdin (push) Failing after 55s
Push translations to Crowdin / Extract and upload translations (push) Failing after 5s
Push website translations to Crowdin / Extract and upload website translations (push) Failing after 5s
CI Create App / create-app-test (test) (push) Has been skipped
CI Create App / create-app-test (typecheck) (push) Has been skipped
CI Docs / docs-lint (push) Has been skipped
CI Example App Hello World / example-app-hello-world (push) Has been skipped
CI Front / front-task (lingui:extract) (push) Has been skipped
CI Front / front-task (test) (push) Has been skipped
CI Front / front-task (typecheck) (push) Has been skipped
CI UI / ui-sb-build (push) Failing after 1m32s
CI Twenty Apps / ${{ matrix.app.name }} (${{ matrix.server-source }}) (push) Has been skipped
CI Agent Skills / agent-skills-publish (push) Has been skipped
CI Create App / ci-create-app-status-check (push) Successful in 2s
CI Agent Skills / agent-skills-remote-source (push) Has been skipped
CI Create App E2E minimal / create-app-e2e-minimal (push) Has been cancelled
CI E2E Main / e2e-test (push) Has been cancelled
CI Front / front-sb-build (push) Has been cancelled
CI Front / front-build (push) Has been cancelled
CI Create App E2E minimal / ci-create-app-e2e-minimal-status-check (push) Has been cancelled
CI E2E Main / ci-e2e-main-status-check (push) Has been cancelled
CI E2E Main / notify-main-ci-failure (push) Has been cancelled
CI E2E Main / qa-scout-comment (push) Has been cancelled
CI Front / front-sb-test (push) Has been cancelled
CI Front / front-sb-screenshots (push) Has been cancelled
CI Front / ci-front-status-check (push) Has been cancelled
DPA Sub-Processor Sync / sync-subprocessors (push) Failing after 3s
AI Catalog Sync / sync-catalog (push) Failing after 2s
265 lines
10 KiB
Plaintext
265 lines
10 KiB
Plaintext
---
|
|
title: Testare
|
|
description: Configurare Vitest, teste de integrare pe un server Twenty real, verificare a tipurilor și CI cu GitHub Actions.
|
|
icon: flask
|
|
---
|
|
|
|
SDK-ul oferă API-uri programatice care vă permit să construiți, să distribuiți, să instalați și să dezinstalați aplicația din codul de test. Combinat cu [Vitest](https://vitest.dev/) și clienții API tipizați, puteți scrie teste de integrare care verifică faptul că aplicația funcționează de la un cap la altul pe un server Twenty real.
|
|
|
|
## Utilizarea pachetelor npm
|
|
|
|
Puteți instala și utiliza orice pachet npm în aplicația dvs. Atât funcţiile logice cât şi componentele frontale sunt grupate cu [esbuild](https://esbuild.github.io/), care înglobează dependențele lor la ieșire - nu sunt necesare `node_modules` în timpul rulării.
|
|
|
|
### Instalarea unui pachet
|
|
|
|
```bash filename="Terminal"
|
|
yarn add axios
|
|
```
|
|
|
|
Apoi importați-l în codul dvs.:
|
|
|
|
```ts src/logic-functions/fetch-data.ts
|
|
import { defineLogicFunction } from 'twenty-sdk/define';
|
|
import axios from 'axios';
|
|
|
|
const handler = async (): Promise<any> => {
|
|
const { data } = await axios.get('https://api.example.com/data');
|
|
|
|
return { data };
|
|
};
|
|
|
|
export default defineLogicFunction({
|
|
universalIdentifier: '...',
|
|
name: 'fetch-data',
|
|
description: 'Fetches data from an external API',
|
|
timeoutSeconds: 10,
|
|
handler,
|
|
});
|
|
```
|
|
|
|
Același lucru funcționează și pentru componentele frontend:
|
|
|
|
```tsx src/front-components/chart.tsx
|
|
import { defineFrontComponent } from 'twenty-sdk/define';
|
|
import { format } from 'date-fns';
|
|
|
|
const DateWidget = () => {
|
|
return <p>Today is {format(new Date(), 'MMMM do, yyyy')}</p>;
|
|
};
|
|
|
|
export default defineFrontComponent({
|
|
universalIdentifier: '...',
|
|
name: 'date-widget',
|
|
component: DateWidget,
|
|
});
|
|
```
|
|
|
|
### Cum funcționează împachetarea
|
|
|
|
Pasul de build folosește esbuild pentru a produce un singur fișier autonom pentru fiecare funcție logică și pentru fiecare componentă frontend. Ambalajele importate sunt încorporate în pachet, cu excepţia celor enumerate mai jos.
|
|
|
|
**Funcțiile logice** rulează într-un mediu Node.js. Modulele built-in Node (`fs`, `path`, `crypto`, `http` etc.) sunt disponibile și nu trebuie instalate.
|
|
|
|
**Componentele frontend** rulează într-un Web Worker. Modulele built-in Node **nu** sunt disponibile — doar pachetele npm care funcționează într-un mediu de browser. Reține că sandbox-ul implementează un DOM *parțial*, astfel încât un pachet se poate construi fără erori, dar totuși poate eșua la execuție; vezi [Limitări curente](/l/ro/developers/extend/apps/layout/front-components#current-limitations).
|
|
|
|
Ambele medii au `twenty-client-sdk/core` și `twenty-client-sdk/metadata` disponibile ca module pre-furnizate — acestea nu sunt incluse în bundle, ci sunt rezolvate la rulare de către server.
|
|
|
|
Componentele frontului pot de asemenea partaja dependențe printr-un [pachet de dependențe partajate](/l/ro/developers/extend/apps/layout/front-components#sharing-dependencies-across-front-components). Pachete listate în câmpul `frontComponentSharedDependencies` din pachetul aplicației. Fiul este construit o dată într-un fișier separat și încărcat din el la rulare în loc să fie înglobat în fiecare componentă, astfel încât o componentă care importă numai pachete comune să nu aibă aproape niciun cod propriu de dependență.
|
|
|
|
## Configurare
|
|
|
|
Aplicația generată (scaffolded) include deja Vitest. Dacă o configurați manual, instalați dependențele:
|
|
|
|
```bash filename="Terminal"
|
|
yarn add -D vitest vite-tsconfig-paths
|
|
```
|
|
|
|
Creați un `vitest.config.ts` în rădăcina aplicației:
|
|
|
|
```ts vitest.config.ts
|
|
import tsconfigPaths from 'vite-tsconfig-paths';
|
|
import { defineConfig } from 'vitest/config';
|
|
|
|
const TWENTY_API_URL = process.env.TWENTY_API_URL ?? 'http://localhost:2020';
|
|
const TWENTY_API_KEY = process.env.TWENTY_API_KEY ?? '<the pre-seeded local dev key>';
|
|
|
|
// Make env vars available to globalSetup (test.env only applies to workers)
|
|
process.env.TWENTY_API_URL = TWENTY_API_URL;
|
|
process.env.TWENTY_API_KEY = TWENTY_API_KEY;
|
|
|
|
export default defineConfig({
|
|
plugins: [
|
|
tsconfigPaths({
|
|
projects: ['tsconfig.spec.json'],
|
|
ignoreConfigErrors: true,
|
|
}),
|
|
],
|
|
test: {
|
|
testTimeout: 120_000,
|
|
hookTimeout: 120_000,
|
|
fileParallelism: false,
|
|
include: ['src/**/*.integration-test.ts'],
|
|
globalSetup: ['src/__tests__/global-setup.ts'],
|
|
env: {
|
|
TWENTY_API_URL,
|
|
TWENTY_API_KEY,
|
|
},
|
|
},
|
|
});
|
|
```
|
|
|
|
Creează un fișier global de configurare inițială care verifică faptul că serverul este accesibil, scrie un fișier de configurare de test pentru SDK (`~/.twenty/config.test.json`) și sincronizează aplicația înainte ca testele să ruleze:
|
|
|
|
```ts src/__tests__/global-setup.ts
|
|
import * as fs from 'fs';
|
|
import * as os from 'os';
|
|
import * as path from 'path';
|
|
|
|
import { appDevOnce, appUninstall } from 'twenty-sdk/cli';
|
|
|
|
const APP_PATH = process.cwd();
|
|
const CONFIG_DIR = path.join(os.homedir(), '.twenty');
|
|
|
|
export async function setup() {
|
|
const apiUrl = process.env.TWENTY_API_URL!;
|
|
const apiKey = process.env.TWENTY_API_KEY!;
|
|
|
|
// Verify the server is running
|
|
const response = await fetch(`${apiUrl}/healthz`);
|
|
if (!response.ok) {
|
|
throw new Error(`Twenty server is not reachable at ${apiUrl}.`);
|
|
}
|
|
|
|
// Write the SDK's test config (the CLI reads config.test.json when NODE_ENV=test)
|
|
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
fs.writeFileSync(
|
|
path.join(CONFIG_DIR, 'config.test.json'),
|
|
JSON.stringify({
|
|
remotes: { local: { apiUrl, apiKey } },
|
|
defaultRemote: 'local',
|
|
}, null, 2),
|
|
);
|
|
|
|
// Start from a clean slate, then sync the app
|
|
await appUninstall({ appPath: APP_PATH }).catch(() => {});
|
|
|
|
const result = await appDevOnce({ appPath: APP_PATH });
|
|
if (!result.success) {
|
|
throw new Error(`Dev sync failed: ${result.error?.message}`);
|
|
}
|
|
}
|
|
|
|
export async function teardown() {
|
|
await appUninstall({ appPath: APP_PATH });
|
|
}
|
|
```
|
|
|
|
## API-uri SDK programatice
|
|
|
|
Subcalea `twenty-sdk/cli` exportă funcții pe care le puteți apela direct din codul de test:
|
|
|
|
| Funcție | Descriere |
|
|
| -------------- | -------------------------------------------------------------------------------------- |
|
|
| `appBuild` | Construiți aplicația și, opțional, împachetați un tarball |
|
|
| `appDeploy` | Încărcați un tarball pe server |
|
|
| `appDevOnce` | Construiește și sincronizează aplicația o singură dată (la fel ca `yarn twenty apply`) |
|
|
| `appInstall` | Instalați aplicația în spațiul de lucru activ |
|
|
| `appUninstall` | Dezinstalați aplicația din spațiul de lucru activ |
|
|
|
|
Fiecare funcție returnează un obiect rezultat cu `success: boolean` și fie `data`, fie `error`.
|
|
|
|
## Scrierea unui test de integrare
|
|
|
|
Iată un exemplu complet care construiește, distribuie și instalează aplicația, apoi verifică faptul că aceasta apare în spațiul de lucru:
|
|
|
|
```ts src/__tests__/app-install.integration-test.ts
|
|
import { APPLICATION_UNIVERSAL_IDENTIFIER } from 'src/application-config';
|
|
import { appBuild, appDeploy, appInstall, appUninstall } from 'twenty-sdk/cli';
|
|
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
|
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
|
|
const APP_PATH = process.cwd();
|
|
|
|
describe('App installation', () => {
|
|
beforeAll(async () => {
|
|
const buildResult = await appBuild({
|
|
appPath: APP_PATH,
|
|
tarball: true,
|
|
onProgress: (message: string) => console.log(`[build] ${message}`),
|
|
});
|
|
|
|
if (!buildResult.success) {
|
|
throw new Error(`Build failed: ${buildResult.error?.message}`);
|
|
}
|
|
|
|
const deployResult = await appDeploy({
|
|
tarballPath: buildResult.data.tarballPath!,
|
|
onProgress: (message: string) => console.log(`[deploy] ${message}`),
|
|
});
|
|
|
|
if (!deployResult.success) {
|
|
throw new Error(`Deploy failed: ${deployResult.error?.message}`);
|
|
}
|
|
|
|
const installResult = await appInstall({ appPath: APP_PATH });
|
|
|
|
if (!installResult.success) {
|
|
throw new Error(`Install failed: ${installResult.error?.message}`);
|
|
}
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await appUninstall({ appPath: APP_PATH });
|
|
});
|
|
|
|
it('should find the installed app in the workspace', async () => {
|
|
const metadataClient = new MetadataApiClient();
|
|
|
|
const result = await metadataClient.query({
|
|
findManyApplications: {
|
|
id: true,
|
|
name: true,
|
|
universalIdentifier: true,
|
|
},
|
|
});
|
|
|
|
const installedApp = result.findManyApplications.find(
|
|
(app: { universalIdentifier: string }) =>
|
|
app.universalIdentifier === APPLICATION_UNIVERSAL_IDENTIFIER,
|
|
);
|
|
|
|
expect(installedApp).toBeDefined();
|
|
});
|
|
});
|
|
```
|
|
|
|
## Rularea testelor
|
|
|
|
Asigurați-vă că serverul Twenty local rulează, apoi:
|
|
|
|
```bash filename="Terminal"
|
|
yarn test
|
|
```
|
|
|
|
Sau în modul watch în timpul dezvoltării:
|
|
|
|
```bash filename="Terminal"
|
|
yarn test:watch
|
|
```
|
|
|
|
## Verificarea tipurilor
|
|
|
|
Puteți rula și verificarea tipurilor pe aplicație fără a rula testele:
|
|
|
|
```bash filename="Terminal"
|
|
yarn twenty dev:typecheck
|
|
```
|
|
|
|
Aceasta rulează `tsc --noEmit` pe fișierul `tsconfig.json` al aplicației și raportează orice erori de tip. Aplicațiile create cu scaffolderul includ, de asemenea, un script `yarn typecheck` care acoperă și fișierele de test (`tsconfig.spec.json`).
|
|
|
|
## CI cu GitHub Actions
|
|
|
|
Scaffolderul generează un workflow gata de utilizare la `.github/workflows/ci.yml`. La fiecare push pe `main` și la fiecare pull request, acesta pornește un server Twenty efemer în runner (prin acțiunea `twentyhq/twenty/.github/actions/spawn-twenty-app-dev-test`), apoi rulează `yarn lint`, `yarn typecheck`, `yarn test:unit` și `yarn test` cu `TWENTY_API_URL` / `TWENTY_API_KEY` îndreptate către acel server. Nu sunt necesare secrete și poți fixa versiunea serverului prin variabila de mediu `TWENTY_VERSION` din partea de sus a workflow-ului.
|
|
|
|
Vezi [Publicare → CI/CD automatizat](/l/ro/developers/extend/apps/operations/publishing#automated-cicd-scaffolded-workflows) pentru un ghid complet al celor trei workflow-uri create cu scaffolderul (`ci.yml`, pipeline-ul de deploy `cd.yml` și `publish.yml` pentru publicare pe npm).
|