92d6bcd8ac
Created by Github action <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23083?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> Co-authored-by: github-actions <github-actions@twenty.com>
263 lines
9.3 KiB
Plaintext
263 lines
9.3 KiB
Plaintext
---
|
|
title: Testes
|
|
description: Configuração do Vitest, testes de integração contra um servidor Twenty real, verificação de tipos e CI com GitHub Actions.
|
|
icon: flask
|
|
---
|
|
|
|
O SDK fornece APIs programáticas que permitem compilar, implantar, instalar e desinstalar seu aplicativo a partir de código de teste. Em conjunto com [Vitest](https://vitest.dev/) e os clientes de API tipados, você pode escrever testes de integração que verificam que seu aplicativo funciona de ponta a ponta em um servidor Twenty real.
|
|
|
|
## Usando pacotes npm
|
|
|
|
Você pode instalar e usar qualquer pacote npm no seu app. Tanto funções lógicas quanto componentes de front-end são empacotados com [esbuild](https://esbuild.github.io/), que incorpora todas as dependências na saída — nenhum `node_modules` é necessário em tempo de execução.
|
|
|
|
### Instalando um pacote
|
|
|
|
```bash filename="Terminal"
|
|
yarn add axios
|
|
```
|
|
|
|
Em seguida, importe-o no seu código:
|
|
|
|
```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,
|
|
});
|
|
```
|
|
|
|
O mesmo vale para componentes de front-end:
|
|
|
|
```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,
|
|
});
|
|
```
|
|
|
|
### Como o empacotamento funciona
|
|
|
|
A etapa de build usa o esbuild para produzir um único arquivo independente por função lógica e por componente de front-end. Todos os pacotes importados são incorporados ao bundle.
|
|
|
|
**Funções lógicas** são executadas em um ambiente Node.js. Módulos nativos do Node (`fs`, `path`, `crypto`, `http`, etc.) estão disponíveis e não precisam ser instalados.
|
|
|
|
**Componentes de front-end** são executados em um Web Worker. Módulos nativos do Node **não** estão disponíveis — apenas APIs do navegador e pacotes npm que funcionam em um ambiente de navegador.
|
|
|
|
Ambos os ambientes têm `twenty-client-sdk/core` e `twenty-client-sdk/metadata` disponíveis como módulos pré-fornecidos — eles não são empacotados, mas resolvidos em tempo de execução pelo servidor.
|
|
|
|
## Configuração
|
|
|
|
O aplicativo gerado pelo scaffolder já inclui o Vitest. Se você configurá-lo manualmente, instale as dependências:
|
|
|
|
```bash filename="Terminal"
|
|
yarn add -D vitest vite-tsconfig-paths
|
|
```
|
|
|
|
Crie um `vitest.config.ts` na raiz do seu aplicativo:
|
|
|
|
```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,
|
|
},
|
|
},
|
|
});
|
|
```
|
|
|
|
Crie um arquivo de configuração global que verifique se o servidor está acessível, escreva uma configuração de teste para o SDK (`~/.twenty/config.test.json`) e sincronize o app antes da execução dos testes:
|
|
|
|
```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 });
|
|
}
|
|
```
|
|
|
|
## APIs programáticas do SDK
|
|
|
|
O subcaminho `twenty-sdk/cli` exporta funções que você pode chamar diretamente a partir do código de teste:
|
|
|
|
| Função | Descrição |
|
|
| -------------- | ---------------------------------------------------------------- |
|
|
| `appBuild` | Compilar o aplicativo e, opcionalmente, empacotar um tarball |
|
|
| `appDeploy` | Enviar um tarball para o servidor |
|
|
| `appDevOnce` | Compila e sincroniza o app uma vez (igual a `yarn twenty apply`) |
|
|
| `appInstall` | Instalar o aplicativo no espaço de trabalho ativo |
|
|
| `appUninstall` | Desinstalar o aplicativo do espaço de trabalho ativo |
|
|
|
|
Cada função retorna um objeto de resultado com `success: boolean` e `data` ou `error`.
|
|
|
|
## Escrevendo um teste de integração
|
|
|
|
Aqui está um exemplo completo que compila, implanta e instala o aplicativo e, em seguida, verifica se ele aparece no espaço de trabalho:
|
|
|
|
```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();
|
|
});
|
|
});
|
|
```
|
|
|
|
## Executando testes
|
|
|
|
Certifique-se de que seu servidor Twenty local esteja em execução e, em seguida:
|
|
|
|
```bash filename="Terminal"
|
|
yarn test
|
|
```
|
|
|
|
Ou no modo watch durante o desenvolvimento:
|
|
|
|
```bash filename="Terminal"
|
|
yarn test:watch
|
|
```
|
|
|
|
## Verificação de tipos
|
|
|
|
Você também pode executar a verificação de tipos no seu aplicativo sem executar os testes:
|
|
|
|
```bash filename="Terminal"
|
|
yarn twenty dev:typecheck
|
|
```
|
|
|
|
Isso executa `tsc --noEmit` no `tsconfig.json` do seu app e informa quaisquer erros de tipo. Os apps criados pelo scaffold também incluem um script `yarn typecheck` que também cobre arquivos de teste (`tsconfig.spec.json`).
|
|
|
|
## CI com GitHub Actions
|
|
|
|
O gerador de scaffold cria um workflow pronto para uso em `.github/workflows/ci.yml`. A cada push para `main` e a cada pull request, ele inicia um servidor Twenty efêmero no runner (por meio da action `twentyhq/twenty/.github/actions/spawn-twenty-app-dev-test`) e então executa `yarn lint`, `yarn typecheck`, `yarn test:unit` e `yarn test` com `TWENTY_API_URL` / `TWENTY_API_KEY` apontando para esse servidor. Nenhum secret é necessário e você pode fixar a versão do servidor por meio da variável de ambiente `TWENTY_VERSION` no topo do workflow.
|
|
|
|
Consulte [Publicação → CI/CD automatizado](/l/pt/developers/extend/apps/operations/publishing#automated-cicd-scaffolded-workflows) para um passo a passo completo dos três workflows criados pelo scaffold (`ci.yml`, o pipeline de deploy `cd.yml` e `publish.yml` para publicação no npm).
|