Skip to content

The open alternative to Salesforce, designed for AI.

7.3 KB
Raw Blame
---
title: Testing
description: Vitest setup, integration tests against a real Twenty server, type checking, and CI with GitHub Actions.
---

import { PageBanner } from "/snippets/page-banner.mdx"

## Overview

Use the standalone CLI with `--json` to build, publish, install, and uninstall your app from test code. Install it globally with `npm install -g twenty`. Combined with [Vitest](https://vitest.dev/) and the typed API clients, you can write integration tests that verify your app works end-to-end against a real Twenty server.

## Using npm packages

You can install and use any npm package in your app. Both logic functions and front components are bundled with [esbuild](https://esbuild.github.io/), which inlines their dependencies into the output — no `node_modules` are needed at runtime.

### Installing a package

```bash filename="Terminal"
yarn add axios
```

Then import it in your code:

```ts src/logic-functions/fetch-data.ts
import { defineLogicFunction } from 'twenty-sdk/define';
import axios from 'axios';

const handler = async () => {
  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,
});
```

The same works for front components:

```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,
});
```

### How bundling works

The build step uses esbuild to produce a single self-contained file per logic function and per front component. Imported packages are inlined into the bundle, except for the ones listed below.

**Logic functions** run in a Node.js environment. Node built-in modules (`fs`, `path`, `crypto`, `http`, etc.) are available and do not need to be installed.

**Front components** run in a Web Worker. Node built-in modules are **not** available — only npm packages that work in a browser environment. Note that the sandbox implements a _partial_ DOM, so a package can build cleanly and still fail at runtime; see [Current limitations](/developers/extend/apps/layout/front-components#current-limitations).

Both environments have `twenty-client-sdk/core` and `twenty-client-sdk/metadata` available as pre-provided modules — these are not bundled but resolved at runtime by the server.

Front components can also share dependencies through a [shared dependencies bundle](/developers/extend/apps/layout/front-components#sharing-dependencies-across-front-components). Packages listed in the `frontComponentSharedDependencies` field of the app's package.json are built once into a separate file and loaded from it at runtime instead of being inlined into each component, so a component that imports only shared packages carries almost no dependency code of its own.

## Setup

The scaffolded app already includes Vitest. If you set it up manually, install the dependencies:

```bash filename="Terminal"
yarn add -D vitest vite-tsconfig-paths
```

Create a `vitest.config.ts` at the root of your app:

```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,
    },
  },
});
```

The generated template includes `src/__tests__/run-twenty.ts`, a subprocess helper that invokes the global CLI and parses its JSON result. Set `TWENTY_CLI` to an absolute executable path to use a local CLI build. It inherits `TWENTY_API_URL` and `TWENTY_API_KEY`; no home-directory config file is needed.

Use this helper for setup and teardown:

```ts src/__tests__/global-setup.ts
import { runTwenty } from './run-twenty';

export async function setup() {
  const result = await runTwenty(['app', 'apply', '--create']);
  if (!result.ok) throw new Error(result.error.message);
}

export async function teardown() {
  const result = await runTwenty(['app', 'uninstall', '--yes']);
  if (!result.ok) throw new Error(result.error.message);
}
```

Run integration tests against a disposable workspace: setup installs the app and teardown uninstalls it. For registry-install coverage, run `app publish --private` followed by `app install` instead of `app apply --create`.

## Writing an integration test

Use `twenty-client-sdk` to inspect data and metadata after the CLI setup completes:

```ts
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
import { expect, it } from 'vitest';
import { APPLICATION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';

it('installs the app', async () => {
  const result = await new MetadataApiClient().query({
    findOneApplication: {
      __args: { universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER },
      id: true,
    },
  });
  expect(result.findOneApplication.id).toBeTruthy();
});
```

For a manifest, read `data.manifest` from `twenty app build --json`. For deployed function tests, use the metadata client's `executeOneLogicFunction` mutation with a user token. Resolve the function within the installed application's ID before invoking it.

## Running tests

Make sure your local Twenty server is running, then:

```bash filename="Terminal"
yarn test
```

Or in watch mode during development:

```bash filename="Terminal"
yarn test:watch
```

## Type checking

You can also run type checking on your app without running tests:

```bash filename="Terminal"
twenty app typecheck
```

This checks your app's `tsconfig.json` with its installed TypeScript compiler, without emitting files, and reports any type errors. Scaffolded apps also ship a `yarn typecheck` script that covers test files too (`tsconfig.spec.json`).

## CI with GitHub Actions

The scaffolder generates a ready-to-use workflow at `.github/workflows/ci.yml`. On every push to `main` and every pull request, it spawns an ephemeral Twenty server in the runner (via the `twentyhq/twenty/.github/actions/spawn-twenty-app-dev-test` action), then runs `yarn lint`, `yarn typecheck`, `yarn test:unit`, and `yarn test` with `TWENTY_API_URL` / `TWENTY_API_KEY` pointing at that server. No secrets are required, and you can pin the server version via the `TWENTY_VERSION` env at the top of the workflow.

See [Publishing → Automated CI/CD](/developers/extend/apps/operations/publishing#automated-cicd-scaffolded-workflows) for a full walkthrough of the three scaffolded workflows (`ci.yml`, the `cd.yml` deploy pipeline, and `publish.yml` for npm publishing).

<PageBanner illustration="card-page-testing" />