Skip to content

Testing Guide

This document describes how to write and run tests for the Teams application.

Testing Strategy

This project follows the Testing Pyramid approach:

        /\
       /  \     E2E Tests (Playwright)
      /    \    - Full user flows
     /------\   - Integration with App Suite
    /        \
   / Unit     \ Unit Tests (Vitest)
  /  Tests     \ - Business logic
 /______________\ - Route handlers
                  - Pinia stores

What We Test at Each Level

Unit Tests (this document):

  • ✅ Business logic and utilities
  • ✅ Route handlers with mocked dependencies
  • ✅ Frontend stores (Pinia)
  • ✅ Database schema validation
  • ✅ Plugin registration

Integration Tests (E2E):

  • ✅ Full user workflows
  • ✅ App Suite API integration (mail, sessions, accounts)
  • ✅ WebSocket real-time collaboration
  • ✅ Authentication flows

What We Don't Test in Unit Tests

The following are tested at higher levels (E2E tests) due to their integration nature:

  • App Suite API calls (src/appsuite/mail.js, src/appsuite/session.js) - Complex HTTP client interactions
  • WebSocket connections (src/routes/ws/ws.js connection handler) - Real-time protocol requires actual connections
  • JWT verification (src/plugins/jwt.js) - Only used in production, bypassed in unit tests via skipAuth

Running Tests

# Run all tests
pnpm test

# Run tests in watch mode
npx vitest --watch

# Run tests with UI
npx vitest --ui

# Run specific test file
npx vitest spec/path/to/test.js

# Run tests with coverage
pnpm test -- --coverage

Test Structure

Tests are organized in the spec/ directory:

  • spec/backend/ - Backend unit tests (Fastify routes, plugins, utilities)
  • spec/frontend/ - Frontend unit tests (Vue components, Pinia stores)
  • spec/util.js - Shared test utilities (Fastify app injection, JWT generation)
  • spec/setup.js - Global test setup and mocks

Writing Tests

Backend Tests

Backend tests use Vitest with the Node.js environment. Example:

import { describe, expect, it } from 'vitest'
import { someFunction } from '../../src/module.js'

describe('Module Name', () => {
  it('should do something', () => {
    const result = someFunction()
    expect(result).toBe(expected)
  })
})

Frontend Tests (Pinia Stores)

Frontend tests use Vitest with Pinia and Vue composables available globally:

import { createPinia, setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it } from 'vitest'

describe('Store Name', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
  })

  it('should manage state', async () => {
    const { useMyStore } = await import('../../ui/teams/stores/my-store.js')
    const store = useMyStore()

    expect(store.someState).toBe(initialValue)
  })
})

Mocking

Global Mocks

The following are mocked globally in spec/setup.js:

  • Vue Router: useRoute() and useRouter()
  • Console methods: All console methods are mocked to reduce test noise
  • Environment variables: LOG_LEVEL=error and NODE_ENV=test

Module Mocks

App Suite external dependencies are aliased in vitest.config.js:

resolve: {
  alias: {
    '$/pinia': 'pinia',
    '$/io.ox/core/extensions': resolve(__dirname, 'spec/__mocks__/io.ox/core/extensions.js'),
    '$/io.ox/core/components': resolve(__dirname, 'spec/__mocks__/io.ox/core/components.js')
  }
}

Add new mocks in spec/__mocks__/ as needed.

Function Mocks

Use Vitest's vi.mock() for mocking modules:

import { vi } from 'vitest'

vi.mock('../../src/db/pool.js', () => ({
  query: vi.fn()
}))

Test Utilities

App Factory Pattern

The application uses a factory pattern for testability:

import { injectApp } from '../util.js'

// Create a test app with authentication disabled
const app = await injectApp({
  db: mockDb,              // Inject mock database
  skipAuth: true,          // Skip JWT authentication
  skipPlugins: ['metrics'], // Skip specific plugins
  testUser: {              // Inject test user (Core UI JWT format)
    userId: 1,             // Numeric user ID
    email: 'test@test.com',
    contextId: 1,
    scope: ['user']
  }
})

await app.ready()

// Test routes using inject
const response = await app.inject({
  method: 'GET',
  url: '/api/threads/me'
})

expect(response.statusCode).toBe(200)

Database Mocking

Create mock databases using the builder pattern:

function createMockDb(responses = []) {
  let callIndex = 0
  const db = {
    select: vi.fn(() => db),
    from: vi.fn(() => db),
    where: vi.fn(() => db),
    then: vi.fn((resolve) => {
      const response = responses[callIndex] || []
      callIndex++
      resolve(response)
      return Promise.resolve(response)
    })
  }
  return db
}

// Use in tests
const mockDb = createMockDb([
  [{ id: 1, inbox: 'test@example.com' }], // First query
  [{ id: 1 }]  // Second query
])

Coverage

Coverage is configured to measure backend code only (src/**/*.js). Reports are generated in output/coverage/.

To view coverage:

pnpm test -- --coverage

Coverage reports are available in:

  • Terminal: Text summary
  • HTML: output/coverage/index.html
  • Cobertura XML: output/coverage/cobertura-coverage.xml (for CI)

Current Coverage

Target: ~75% for unit-testable code

Well-Covered Areas:

  • Routes: 86-98% (threads, mail, accounts)
  • Database: 89%
  • Core app: 82%

Low Coverage (Intentional):

  • App Suite API integration: 0-12% (tested in E2E)
  • WebSocket connections: 11% (setup tested, connections in E2E)
  • JWT plugin: 0% (production-only, bypassed in tests)

Best Practices

  • Isolation: Each test should be independent and not rely on shared state
  • Descriptive names: Use clear, descriptive test names that explain what is being tested
  • AAA pattern: Arrange, Act, Assert - structure tests clearly
  • Clean up: Use beforeEach and afterEach to set up and tear down test state
  • Mock external dependencies: Don't make real HTTP requests or database calls in unit tests

CI Integration

Tests run automatically in CI via .gitlab-ci.yml. The pipeline:

  1. Runs all tests with pnpm test -- --run
  2. Generates JUnit XML report in output/junit.xml
  3. Generates Cobertura coverage report in output/coverage/cobertura-coverage.xml
  4. Reports coverage percentage in the pipeline

Troubleshooting

Tests failing with "module not found"

Check that:

  • Module paths are correct (use relative imports)
  • Aliases are configured in vitest.config.js
  • Mocks exist in spec/__mocks__/

Vue composables not defined

Make sure spec/setup.js is loaded (configured in vitest.config.js). The setup file provides global Vue composables.

Coverage not showing frontend code

Coverage is currently configured for backend only (src/**/*.js). To measure frontend coverage, update vitest.config.js:

coverage: {
  include: ['src/**/*.js', 'ui/**/*.js']
}