Testing Strategy
Relevant source files
The following files were used as context for generating this wiki page:
- CLAUDE.md
- packages/twenty-e2e-testing/playwright.config.ts
- packages/twenty-server/jest-integration.config.ts
- packages/twenty-front/setupTests.ts
- packages/twenty-server/test/integration/utils/setup-test.ts
- packages/twenty-e2e-testing/README.md
- packages/twenty-server/test/integration/graphql/codegen/index.ts
- packages/twenty-server/src/engine/metadata-modules/page-layout/services/tests/page-layout.service.spec.ts
- packages/twenty-front/src/modules/advanced-text-editor/components/stories/AdvancedTextEditor.stories.tsx
- packages/twenty-utils/dangerfile.ts
- packages/twenty-server/test/integration/rest/suites/page-layout.integration-spec.ts
The Twenty project employs a comprehensive, multi-layered testing strategy to ensure code quality, stability, and correctness across its frontend, backend, and shared packages. The strategy encompasses unit tests, integration tests, end-to-end (E2E) tests, and component-level tests using Storybook. This approach validates individual pieces of logic in isolation, verifies the interactions between different parts of the system, and confirms that critical user flows work as expected from a user's perspective.
The entire testing suite is managed within an Nx monorepo, allowing for granular test execution per package. The strategy is supported by a combination of tools including Jest for unit and integration testing, Playwright for E2E testing, and Storybook for UI component testing.
High-Level Overview
The testing strategy is structured in four primary layers, each targeting a different scope of the application.
This diagram shows the layered testing approach, from broad end-to-end tests to specific unit tests.
| Test Type | Package | Tool | Purpose |
|---|---|---|---|
| Unit Tests | twenty-front, twenty-server | Jest | Test individual functions and services in isolation. |
| Integration Tests | twenty-server | Jest, Supertest | Test critical backend workflows and API endpoints (REST & GraphQL). |
| Component Tests | twenty-front | Storybook | Develop, visualize, and test UI components in isolation. |
| E2E Tests | twenty-e2e-testing | Playwright | Test critical user flows across the entire application stack. |
Sources: CLAUDE.md:80-83
Test Execution Commands
The Nx workspace provides a set of commands to run the various test suites.
| Command | Description |
|---|---|
npx nx test twenty-front | Runs frontend unit tests. |
npx nx test twenty-server | Runs backend unit tests. |
npx nx run twenty-server:test:integration:with-db-reset | Runs backend integration tests with a database reset. |
npx nx storybook:serve-and-test:static twenty-front | Runs Storybook interaction tests. |
npx nx test twenty-e2e-testing | Runs Playwright end-to-end tests. |
Sources: CLAUDE.md:18-25, packages/twenty-e2e-testing/README.md:9
Unit Testing
Unit tests focus on the smallest parts of the application, such as individual services or utility functions, mocking any external dependencies.
Backend Unit Tests (twenty-server)
Backend unit tests use Jest and NestJS's testing utilities to test services and controllers. Dependencies like database repositories are mocked to ensure tests are fast and isolated.
A typical backend unit test suite for a service like PageLayoutService involves:
- Creating a NestJS testing module using
Test.createTestingModule. - Providing mock implementations for dependencies, such as TypeORM repositories (
getRepositoryToken). - Writing individual test cases for each service method (
describeanditblocks). - Using Jest's mocking capabilities (
jest.fn(),jest.spyOn()) to control the behavior of dependencies and assert that they are called correctly.
Frontend Unit Tests (twenty-front)
Frontend unit tests also use Jest. A global setup file configures the test environment before tests are run. This includes polyfills and mocks for browser-specific APIs that are not available in the Node.js environment where Jest runs.
The setup file setupTests.ts performs actions like:
- Mocking
window.matchMedia. - Setting up
whatwg-fetchfor network request mocking.
Sources: packages/twenty-front/setupTests.ts
Integration Testing (twenty-server)
Integration tests for the backend are designed to test complete workflows and API endpoints, including interaction with a real database.
Configuration and Setup
Integration tests have a dedicated Jest configuration file.
Key configuration options in jest-integration.config.ts:
testEnvironment: Set to'node'.setupFilesAfterEnv: Points to a setup file (<rootDir>/test/integration/utils/setup-test.ts) that runs before each test suite.testMatch: Specifies the pattern for discovering integration test files (**/*.integration-spec.ts).
Sources: packages/twenty-server/jest-integration.config.ts:3-13
The setup process, managed by setup-test.ts, handles loading environment variables and defines global beforeAll and afterAll hooks to manage the test environment lifecycle.
Sources: packages/twenty-server/test/integration/utils/setup-test.ts
REST and GraphQL API Testing
Integration tests cover both REST and GraphQL APIs to ensure they behave as expected.
- REST API Tests: Use the
supertestlibrary to make HTTP requests to the running application and assert responses. Tests cover CRUD operations, filtering, error handling, and edge cases. - GraphQL API Tests: Use a custom
makeGraphqlAPIRequestutility, which is likely built on top of an HTTP client, to send GraphQL queries and mutations. Assertions are made on the response body, checking fordataand the absence oferrors.
The following diagram shows a typical integration test flow for a REST endpoint.
This sequence shows an integration test creating a new pageLayout via the REST API and asserting the successful response.
Sources: packages/twenty-server/test/integration/rest/suites/page-layout.integration-spec.ts:102-114, packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-update-with-tabs-and-widgets.integration-spec.ts:178-184
End-to-End (E2E) Testing
E2E tests validate complete user journeys from the UI to the backend. The twenty-e2e-testing package uses Playwright for this purpose.
Configuration
The playwright.config.ts file defines the core configuration for E2E tests.
- Projects: Configures tests to run against multiple browsers (Chromium, Firefox, WebKit).
baseURL: Specifies the target URL for the application under test.trace: Set to'on-first-retry', which records a detailed trace of failed tests upon retry, aiding in debugging.use: Contains global settings for all test runs, including thebaseURLand trace options.
Sources: packages/twenty-e2e-testing/playwright.config.ts:25-56
E2E Commands
A set of nx commands is available for running and managing E2E tests.
| Command | Description |
|---|---|
npx nx setup twenty-e2e-testing | Installs the necessary browser binaries. |
npx nx test twenty-e2e-testing | Runs all E2E tests. |
npx nx test:ui twenty-e2e-testing | Starts Playwright in interactive UI mode. |
npx nx test:debug twenty-e2e-testing | Runs tests in debug mode. |
npx nx test:report twenty-e2e-testing | Shows the HTML report of the last test run. |
Sources: packages/twenty-e2e-testing/README.md:5-24
Component Testing with Storybook
Storybook is used in the twenty-front package for developing, documenting, and testing React components in isolation.
Story Structure and Interaction Testing
Stories are written in MDX or TSX format. A key feature is the use of a play function to script user interactions and assertions, powered by @storybook/test.
An example from AdvancedTextEditor.stories.tsx demonstrates:
- Decorators: Stories are wrapped with decorators (
ComponentDecorator,RouterDecorator,I18nFrontDecorator, etc.) to provide necessary application context like routing, state management, and internationalization. playfunction: It usesuserEventto simulate user actions like clicks and typing.- Assertions: It uses
expectfrom@storybook/testto verify the component's state and DOM output after an interaction.
// packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx:324-340
export const WithLists: Story = {
// ...args
play: async ({ canvasElement, step }) => {
await step('Verify bullet list is rendered', async () => {
await waitFor(() =>
expect(canvasElement.querySelectorAll('ul li').length).toBeGreaterThan(
0,
),
);
const listItems = canvasElement.querySelectorAll('ul li');
const firstItem = listItems[0];
expect(firstItem).toBeInTheDocument();
expect(firstItem).toHaveTextContent(/User authentication system/i);
});
// ... more steps
},
};
Automated Workflows
The project includes automated scripts for both test generation and code quality checks.
GraphQL Test Generation
A script exists to automatically generate basic integration tests for GraphQL queries. This helps ensure baseline coverage for the GraphQL API.
The process is as follows:
- Fetch Schema: It sends an introspection query to the running GraphQL endpoint.
- Filter Queries: It iterates through the query fields, filtering out those that require arguments to avoid complexity.
- Generate Content: For each valid query, it generates a test file content string with a basic test case. The test queries for all scalar/enum fields on the return type.
- Write File: The generated content is written to a
.integration-spec.tsfile. It can skip existing files or overwrite them if the--forceflag is used.
This flowchart illustrates the automated generation of GraphQL integration tests.
Sources: packages/twenty-server/test/integration/graphql/codegen/index.ts
CI Code Quality Checks
The project uses danger.js to perform automated checks on pull requests, ensuring adherence to project conventions.
Key checks in dangerfile.ts:
- Dependency Consistency: Warns if
package.jsonis changed butyarn.lockis not. - Configuration Documentation: Warns if
.env.exampleis changed, reminding the developer to update configuration metadata. - Contributor License Agreement (CLA): Welcomes first-time contributors and reminds them of the CLA.
- TODOs/FIXMEs: Schedules a check to report any
TODOorFIXMEcomments left in the code.
Sources: packages/twenty-utils/dangerfile.ts