Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
docs: refresh testing strategy and development guidelines (#386)
Yudhi Armyndharis264ca6c60cb4
diff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.mdindex e8c60d3f1..14859684e 100644--- a/docs/08-development-guidelines.md+++ b/docs/08-development-guidelines.md@@ -7,67 +7,26 @@ openwa/├── src/│ ├── main.ts # Application entry│ ├── app.module.ts # Root module-│ │-│ ├── common/ # Shared code-│ │ ├── decorators/-│ │ ├── dto/-│ │ ├── exceptions/-│ │ ├── filters/-│ │ ├── guards/-│ │ ├── interceptors/-│ │ ├── interfaces/-│ │ ├── pipes/-│ │ └── utils/-│ │-│ ├── config/ # Configuration-│ │ ├── config.module.ts-│ │ └── configuration.ts-│ │-│ ├── modules/ # Feature modules-│ │ ├── session/-│ │ ├── message/-│ │ ├── webhook/-│ │ ├── contact/-│ │ ├── group/-│ │ ├── auth/-│ │ └── health/-│ │-│ ├── engine/ # WhatsApp engine-│ │ ├── engine.module.ts-│ │ ├── engine.service.ts-│ │ └── interfaces/-│ │-│ ├── queue/ # Job queues-│ │ ├── queue.module.ts-│ │ └── processors/-│ │-│ └── database/ # Database-│ ├── database.module.ts-│ ├── entities/-│ └── migrations/-│-├── test/ # Tests-│ ├── unit/-│ ├── integration/-│ └── e2e/-│-├── dashboard/ # Frontend dashboard-│ ├── src/-│ └── package.json-│+│ ├── common/ # Shared cache, security, storage, errors, utils+│ ├── config/ # Runtime config, env validation, bootstrap security, Swagger+│ ├── core/ # Hook and plugin framework+│ ├── database/ # TypeORM data sources and migrations+│ ├── engine/ # WhatsApp engine abstraction, adapters, identity mapping+│ ├── modules/ # API feature modules+│ └── plugins/ # Built-in engine and extension plugins+├── test/ # E2E smoke tests and mocks+├── dashboard/ # React/Vite dashboard+├── sdk/ # JavaScript and Python SDK scaffolds├── docs/ # Documentation├── scripts/ # Utility scripts-├── docker/ # Docker files-│-├── .github/ # GitHub config-│ └── workflows/-│+├── .github/workflows/ # CI and release workflows├── package.json├── tsconfig.json├── nest-cli.json-├── .eslintrc.js-├── .prettierrc+├── eslint.config.mjs├── docker-compose.yml+├── docker-compose.dev.yml+├── Dockerfile└── README.md```@@ -108,34 +67,20 @@ openwa/### ESLint Configuration-```javascript-// .eslintrc.js-module.exports = {- parser: '@typescript-eslint/parser',- parserOptions: {- project: 'tsconfig.json',- sourceType: 'module',- },- plugins: ['@typescript-eslint/eslint-plugin'],- extends: [- 'plugin:@typescript-eslint/recommended',- 'plugin:prettier/recommended',- ],- root: true,- env: {- node: true,- jest: true,- },- ignorePatterns: ['.eslintrc.js'],- rules: {- '@typescript-eslint/interface-name-prefix': 'off',- '@typescript-eslint/explicit-function-return-type': 'warn',- '@typescript-eslint/explicit-module-boundary-types': 'warn',- '@typescript-eslint/no-explicit-any': 'warn',- '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],- 'no-console': 'warn',- },-};+The backend uses ESLint flat config in `eslint.config.mjs` with type-aware TypeScript rules,+Prettier integration, and an architecture guard for controllers. HTTP controllers must call+capability services; they must not import `IWhatsAppEngine` or call `getEngine()` directly.++```bash+npm run lint+npm run lint:fix+```++The dashboard has its own package scripts:++```bash+cd dashboard+npm run lint```### Naming Conventions@@ -189,7 +134,7 @@ import { ExampleRepository } from './example.repository';import { Example } from './entities/example.entity';@Module({- imports: [TypeOrmModule.forFeature([Example])],+ imports: [TypeOrmModule.forFeature([Example], 'data')],controllers: [ExampleController],providers: [ExampleService, ExampleRepository],exports: [ExampleService],@@ -209,19 +154,16 @@ import {Headers,Param,Delete,- UseGuards,HttpCode,HttpStatus,} from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';-import { ApiKeyGuard } from '@common/guards/api-key.guard';import { ExampleService } from './example.service';import { CreateExampleDto } from './dto/create-example.dto';import { ExampleResponseDto } from './dto/example-response.dto';@ApiTags('examples')@Controller('examples')-@UseGuards(ApiKeyGuard)export class ExampleController {constructor(private readonly exampleService: ExampleService) {}@@ -252,6 +194,11 @@ export class ExampleController {}```+Controllers are protected by the global API key guard unless marked with `@Public()`. Keep+controllers thin: validate transport input through DTOs, delegate behavior to services, and never+call `SessionService.getEngine()` directly from a controller. Engine-specific details belong behind+capability services and engine adapters.+### Service Template```typescript@@ -432,87 +379,34 @@ Closes #### Test Structure+Unit tests live next to source files as `*.spec.ts`. E2E smoke tests live in `test/`.+```+src/+├── common/security/ssrf-guard.spec.ts+├── engine/adapters/baileys.adapter.spec.ts+├── modules/session/session.service.spec.ts+└── modules/webhook/webhook.service.spec.ts+test/-├── unit/ # Unit tests-│ ├── services/-│ │ ├── session.service.spec.ts-│ │ └── message.service.spec.ts-│ └── utils/-│ └── encryption.spec.ts-│-├── integration/ # Integration tests-│ ├── session.integration.spec.ts-│ └── webhook.integration.spec.ts-│-└── e2e/ # End-to-end tests- ├── app.e2e-spec.ts- └── session.e2e-spec.ts+├── app.e2e-spec.ts+├── baileys-engine.e2e-spec.ts+├── serve-static.e2e-spec.ts+├── jest-e2e.json+└── setup-e2e.ts```### Unit Test Example```typescript-// test/unit/services/session.service.spec.ts-import { Test, TestingModule } from '@nestjs/testing';-import { SessionService } from '@modules/session/session.service';-import { SessionRepository } from '@modules/session/session.repository';-import { EngineService } from '@engine/engine.service';--describe('SessionService', () => {- let service: SessionService;- let repository: jest.Mocked<SessionRepository>;- let engineService: jest.Mocked<EngineService>;-- beforeEach(async () => {- const module: TestingModule = await Test.createTestingModule({- providers: [- SessionService,- {- provide: SessionRepository,- useValue: {- create: jest.fn(),- save: jest.fn(),- findOne: jest.fn(),- delete: jest.fn(),- },- },- {- provide: EngineService,- useValue: {- createClient: jest.fn(),- destroyClient: jest.fn(),- },- },- ],- }).compile();-- service = module.get<SessionService>(SessionService);- repository = module.get(SessionRepository);- engineService = module.get(EngineService);- });-- describe('create', () => {- it('should create a new session', async () => {- const dto = { name: 'test-session' };- const session = { id: 'uuid', ...dto, status: 'created' };-- repository.create.mockReturnValue(session as any);- repository.save.mockResolvedValue(session as any);-- const result = await service.create(dto);-- expect(result).toEqual(session);- expect(repository.create).toHaveBeenCalledWith(dto);- expect(repository.save).toHaveBeenCalled();- });-- it('should throw error if name already exists', async () => {- const dto = { name: 'existing-session' };-- repository.save.mockRejectedValue({ code: '23505' }); // Unique violation-- await expect(service.create(dto)).rejects.toThrow();+// src/modules/session/reconnect-config.spec.ts+import { resolveReconnectConfig } from './session.service';++describe('resolveReconnectConfig', () => {+ it('keeps reconnect settings finite and bounded', () => {+ expect(resolveReconnectConfig({ maxReconnectAttempts: 'bad', reconnectBaseDelay: -1 })).toEqual({+ maxAttempts: 5,+ baseDelay: 1000,});});});@@ -521,15 +415,14 @@ describe('SessionService', () => {### E2E Test Example```typescript-// test/e2e/session.e2e-spec.ts+// test/app.e2e-spec.tsimport { Test, TestingModule } from '@nestjs/testing';import { INestApplication } from '@nestjs/common';import * as request from 'supertest';-import { AppModule } from '@/app.module';+import { AppModule } from '../src/app.module';-describe('Session (e2e)', () => {+describe('App (e2e)', () => {let app: INestApplication;- const apiKey = 'test-api-key';beforeAll(async () => {const moduleFixture: TestingModule = await Test.createTestingModule({@@ -544,36 +437,31 @@ describe('Session (e2e)', () => {await app.close();});- describe('POST /api/sessions', () => {- it('should create a session', () => {+ describe('GET /api/health', () => {+ it('returns health status without an API key', () => {return request(app.getHttpServer())- .post('/api/sessions')- .set('X-API-Key', apiKey)- .send({ name: 'e2e-test-session' })- .expect(201)+ .get('/api/health')+ .expect(200).expect((res) => {- expect(res.body.name).toBe('e2e-test-session');- expect(res.body.status).toBe('created');+ expect(res.body.status).toBe('ok');});});-- it('should return 401 without API key', () => {- return request(app.getHttpServer())- .post('/api/sessions')- .send({ name: 'test' })- .expect(401);- });});});```### Test Coverage Requirements-| Type | Minimum Coverage |-|------|-----------------|-| Unit Tests | 80% |-| Integration Tests | 60% |-| E2E Tests | Critical paths |+Run the normal backend checks before opening a PR:++```bash+npm test -- --runInBand+npm run test:e2e -- --runInBand+npm run lint+```++Coverage thresholds are enforced by Jest in `package.json`. Security-sensitive code under+`src/common/security/` has stricter thresholds than the global baseline.## 8.6 Documentation Standards@@ -723,22 +611,31 @@ export class AllExceptionsFilter implements ExceptionFilter {```bash# 1. Clone repositorygit clone https://github.com/rmyndharis/OpenWA.git-cd openwa+cd OpenWA-# 2. Install dependencies+# 2. Install dependencies (also installs dashboard dependencies)npm install-# 3. Copy environment file-cp .env.example .env+# 3. Start API + dashboard in development mode+npm run dev+```-# 4. Start infrastructure services-docker compose up -d postgres redis+On first boot the API creates `data/.env.generated` with a minimal SQLite/local-storage+configuration. A project-level `.env` is optional; real process environment variables take precedence+over `.env`, which takes precedence over `data/.env.generated`.-# 5. Run database migrations-npm run migration:run+For a production-image local smoke test:-# 6. Start development server-npm run start:dev+```bash+docker compose -f docker-compose.dev.yml up -d --build+```++For production compose:++```bash+docker compose up -d+docker compose --profile postgres up -d+docker compose --profile full up -d```### VS Code Extensions@@ -750,7 +647,6 @@ npm run start:dev"dbaeumer.vscode-eslint","esbenp.prettier-vscode","ms-azuretools.vscode-docker",- "prisma.prisma","humao.rest-client","bradlc.vscode-tailwindcss","orta.vscode-jest"@@ -783,8 +679,6 @@ OpenWA supports multiple infrastructure configurations. Choose based on your nee#### Minimal Profile (Development / Single Session)```bash-# .env.example (Minimal Profile)-# ApplicationNODE_ENV=developmentPORT=2785@@ -792,36 +686,34 @@ LOG_LEVEL=debug# Database: SQLite (zero config)DATABASE_TYPE=sqlite-DATABASE_SQLITE_PATH=./data/openwa.db+DATABASE_NAME=./data/openwa.sqlite+DATABASE_SYNCHRONIZE=true# Storage: Local filesystemSTORAGE_TYPE=local-STORAGE_LOCAL_PATH=./media+STORAGE_LOCAL_PATH=./data/media-# Cache: In-memory (no Redis needed)-CACHE_TYPE=memory+# Redis and queue disabled by default+REDIS_ENABLED=false+QUEUE_ENABLED=false-# Security-ENCRYPTION_KEY=dev-encryption-key-change-in-production-API_KEY_MASTER=dev-master-key-change-in-production+# Optional: seed a known admin key. If omitted, OpenWA generates a random key and writes data/.api-key.+API_MASTER_KEY=# Session-SESSION_DATA_PATH=./.wwebjs_auth-MAX_SESSIONS=3+SESSION_DATA_PATH=./data/sessions-# Engine (whatsapp-web.js = default, Chromium-based; baileys = browser-free WebSocket)+# Engine: whatsapp-web.js = Chromium-based; baileys = browser-free WebSocketENGINE_TYPE=whatsapp-web.jsPUPPETEER_HEADLESS=true-# Development-SWAGGER_ENABLED=true+# Swagger is enabled by default. Set false to disable.+ENABLE_SWAGGER=true```#### Standard Profile (Production / Multi-Session)```bash-# .env.example (Standard Profile)-# ApplicationNODE_ENV=productionPORT=2785@@ -829,34 +721,41 @@ LOG_LEVEL=info# Database: PostgreSQLDATABASE_TYPE=postgres-DATABASE_URL=postgresql://openwa:openwa@localhost:5432/openwa+DATABASE_HOST=postgres+DATABASE_PORT=5432+DATABASE_USERNAME=openwa+DATABASE_PASSWORD=<set-a-strong-password>+DATABASE_NAME=openwa+DATABASE_SYNCHRONIZE=false+DATABASE_POOL_SIZE=10# Storage: Local filesystemSTORAGE_TYPE=local-STORAGE_LOCAL_PATH=./media+STORAGE_LOCAL_PATH=/app/data/media# Cache: Redis-CACHE_TYPE=redis-REDIS_URL=redis://localhost:6379+REDIS_ENABLED=true+REDIS_HOST=redis+REDIS_PORT=6379+QUEUE_ENABLED=true-# Security (generate with: openssl rand -base64 32)-ENCRYPTION_KEY=your-32-byte-encryption-key-here-API_KEY_MASTER=your-secure-master-key+# Security+API_MASTER_KEY=<set-a-strong-initial-admin-key>+API_KEY_PEPPER=<optional-hash-pepper>+CORS_ORIGINS=https://dashboard.example.com# Session-SESSION_DATA_PATH=./.wwebjs_auth-MAX_SESSIONS=10+SESSION_DATA_PATH=/app/data/sessions-# Engine (whatsapp-web.js = default, Chromium-based; baileys = browser-free WebSocket)+# EngineENGINE_TYPE=whatsapp-web.jsPUPPETEER_HEADLESS=true--# Development-SWAGGER_ENABLED=true+PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu+ENABLE_SWAGGER=false```> [!TIP]-> For development, use the **Minimal Profile** with SQLite. No need to set up PostgreSQL or Redis.+> For development, use the minimal profile with SQLite. PostgreSQL, Redis, and S3/MinIO are optional.## 8.9 Debugging Guide@@ -1030,35 +929,17 @@ const sessions = await sessionRepo### Caching Strategy```typescript-// Cache frequently accessed data+// CacheService exposes typed helpers; prefer those over ad hoc string keys in feature code.@Injectable()-export class SessionService {- constructor(- private readonly cache: CacheService,- private readonly repo: SessionRepository,- ) {}-- async getSession(id: string): Promise<Session> {- // Check cache first- const cached = await this.cache.get<Session>(`session:${id}`);- if (cached) return cached;-- // Fetch from database- const session = await this.repo.findOne({ where: { id } });-- // Cache for 5 minutes- await this.cache.set(`session:${id}`, session, 300);-- return session;+export class SessionStatsService {+ constructor(private readonly cache: CacheService) {}++ async getCachedStats(): Promise<SessionStats | null> {+ return this.cache.getSessionsStats();}-- async updateSession(id: string, data: Partial<Session>): Promise<Session> {- const session = await this.repo.update(id, data);-- // Invalidate cache- await this.cache.del(`session:${id}`);-- return session;++ async updateCachedStats(stats: SessionStats): Promise<void> {+ await this.cache.setSessionsStats(stats);}}```@@ -1090,25 +971,20 @@ const results = await Promise.all(### Memory Management```typescript-// Session cleanup to prevent memory leaks+// Bound teardown so one stuck browser/socket cannot block shutdown.@Injectable()-export class SessionCleanupService {- private readonly logger = new Logger(SessionCleanupService.name);-- @Cron('0 */5 * * * *') // Every 5 minutes- async cleanupInactiveSessions(): Promise<void> {- const inactiveThreshold = new Date(Date.now() - 30 * 60 * 1000); // 30 min-- const inactiveSessions = await this.sessionRepo.find({- where: {- status: 'disconnected',- updatedAt: LessThan(inactiveThreshold),- },+export class EngineTeardownService {+ private readonly logger = new Logger(EngineTeardownService.name);++ async destroyWithTimeout(sessionId: string, engine: IWhatsAppEngine): Promise<void> {+ const timeout = new Promise<never>((_, reject) => {+ setTimeout(() => reject(new Error('engine.destroy() timed out')), 10_000);});-- for (const session of inactiveSessions) {- await this.engineService.destroy(session.id);- this.logger.log(`Cleaned up inactive session: ${session.id}`);++ try {+ await Promise.race([engine.destroy(), timeout]);+ } catch (error) {+ this.logger.warn(`Engine teardown failed for ${sessionId}: ${String(error)}`);}}}@@ -1129,7 +1005,8 @@ export class SessionCleanupService {- Check Puppeteer args: `--no-sandbox --disable-setuid-sandbox`2. **Previous session data corrupted**- - Clear session folder: `rm -rf .wwebjs_auth/session-{id}`+ - Clear the stored auth/session data for the session under `data/sessions`+ - For Baileys, also check `BAILEYS_AUTH_DIR` (default `./data/baileys`)3. **WhatsApp rate limit**- Wait 5-10 minutes before retrying@@ -1184,7 +1061,7 @@ npm run migration:shownpm run migration:revert# Regenerate migration-npm run migration:generate -- -n FixMigration+npm run migration:generate --name=FixMigration``````@@ -1229,7 +1106,7 @@ constructor(**Check logs:**```bash-docker compose logs app --tail 100+docker compose logs openwa-api --tail 100```**Common causes:**@@ -1248,7 +1125,7 @@ docker run --shm-size=2gb openwaOr in docker-compose.yml:```yamlservices:- app:+ openwa-api:shm_size: '2gb'``````diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex f2a69d4e2..72ee49bde 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -1,721 +1,227 @@# 09 - Testing Strategy-## Implementation Status--> **Current Status: Minimal Implementation**->-> This document outlines the planned testing strategy for OpenWA. The current implementation includes only foundational tests:->-> | Test Type | Planned | Actual |-> |-----------|---------|--------|-> | Unit Tests | 60% coverage | 3 files |-> | Integration Tests | 30% coverage | Not yet |-> | E2E Tests | Critical paths | Not yet |->-> **Existing test files:**-> - `src/common/services/logger.service.spec.ts` - Logger functionality-> - `src/modules/health/health.controller.spec.ts` - Health endpoints-> - `src/modules/webhook/utils/idempotency.util.spec.ts` - Idempotency utilities->-> Comprehensive testing is planned for future releases. The strategy below serves as a guide for contributors and future development phases.+## 09.1 Current Status------## 09.1 Overview--```mermaid-flowchart TB- subgraph TestPyramid["Testing Pyramid"]- direction TB- E2E[E2E Tests<br/>10%]- INT[Integration Tests<br/>30%]- UNIT[Unit Tests<br/>60%]- end-- subgraph Types["Test Types"]- UT[Unit Tests]- IT[Integration Tests]- ET[E2E Tests]- PT[Performance Tests]- ST[Security Tests]- end-```--### Testing Goals+OpenWA now has an active Jest test suite covering the backend core, engine adapters, security helpers,+database migrations, plugin hooks, and smoke-level e2e boot paths. This document describes the current+test layout and the expected testing workflow for contributors.-| Goal | Target | Current | Priority |-|------|--------|---------|----------|-| Code Coverage | > 80% | ~5% | High |-| Integration Test Coverage | > 70% | 0% | High |-| E2E Critical Paths | 100% | 0% | High |-| Performance Benchmarks | Pass all | Not started | Medium |-| Security Scan | 0 Critical | ✅ Passing | High |+Status snapshot from the repository state on 2026-06-21:-## 09.2 Unit Testing--### Framework & Tools--```json-{- "devDependencies": {- "jest": "^29.0.0",- "@nestjs/testing": "^10.0.0",- "ts-jest": "^29.0.0"- }-}-```+| Area | Current state |+|------|---------------|+| Backend unit tests | 89 Jest suites / 987 tests passing with `npm test -- --runInBand` |+| E2E smoke tests | 3 Jest suites / 11 tests passing with `npm run test:e2e -- --runInBand` |+| Test files | 92 `*.spec.ts` / `*.e2e-spec.ts` files under `src/` and `test/` |+| Dashboard checks | CI runs dashboard lint, i18n parity check, and dashboard build |+| Coverage gate | Jest global thresholds plus stricter thresholds for security-sensitive modules |-### Test Structure+The exact counts will change as the project evolves. Use the commands below as the source of truth.+```bash+find src test -name '*.spec.ts' -o -name '*.e2e-spec.ts' | wc -l+npm test -- --runInBand+npm run test:e2e -- --runInBand```-src/-├── modules/-│ ├── session/-│ │ ├── session.service.ts-│ │ └── session.service.spec.ts-│ ├── message/-│ │ ├── message.service.ts-│ │ └── message.service.spec.ts-│ └── webhook/-│ ├── webhook.service.ts-│ └── webhook.service.spec.ts-└── common/- └── utils/- ├── validator.ts- └── validator.spec.ts-```--### Unit Test Examples--```typescript-// session.service.spec.ts-describe('SessionService', () => {- let service: SessionService;- let engineFactory: jest.Mocked<EngineFactory>;- let repository: jest.Mocked<SessionRepository>;-- beforeEach(async () => {- const module = await Test.createTestingModule({- providers: [- SessionService,- {- provide: EngineFactory,- useValue: createMock<EngineFactory>(),- },- {- provide: SessionRepository,- useValue: createMock<SessionRepository>(),- },- ],- }).compile();-- service = module.get(SessionService);- engineFactory = module.get(EngineFactory);- repository = module.get(SessionRepository);- });-- describe('createSession', () => {- it('should create a new session with default config', async () => {- const dto = { name: 'test-session' };- repository.findByName.mockResolvedValue(null);- repository.save.mockResolvedValue({ id: 'sess_123', ...dto });- const result = await service.createSession(dto);+## 09.2 Test Commands- expect(result.id).toBe('sess_123');- expect(repository.save).toHaveBeenCalledWith(- expect.objectContaining({ name: 'test-session' })- );- });+| Command | Purpose |+|---------|---------|+| `npm test` | Run backend Jest unit tests from `src/` |+| `npm test -- --runInBand` | Run backend tests serially; useful for local debugging and clean output |+| `npm run test:cov` | Run backend tests with coverage and coverage thresholds |+| `npm run test:e2e` | Run smoke-level e2e tests from `test/` |+| `npm run lint` | Run backend ESLint with type-aware rules |+| `cd dashboard && npm run lint` | Run dashboard ESLint |+| `cd dashboard && npm run i18n:check` | Verify dashboard locale key parity |+| `cd dashboard && npm run build` | Type-check and build the dashboard |- it('should throw error if session name already exists', async () => {- const dto = { name: 'existing-session' };- repository.findByName.mockResolvedValue({ id: 'sess_old' });+## 09.3 Backend Unit Tests- await expect(service.createSession(dto))- .rejects.toThrow('SESSION_ALREADY_EXISTS');- });- });-- describe('sendMessage', () => {- it('should validate chatId format', async () => {- const invalidChatId = 'invalid-format';+Backend unit tests live next to the source files they cover:- await expect(- service.sendMessage('sess_123', invalidChatId, 'Hello')- ).rejects.toThrow('MESSAGE_INVALID_CHAT_ID');- });- });-});+```text+src/+├── common/+│ ├── security/+│ │ ├── ssrf-guard.ts+│ │ └── ssrf-guard.spec.ts+│ └── storage/+│ ├── storage.service.ts+│ └── storage.service.spec.ts+├── engine/+│ ├── adapters/+│ │ ├── baileys.adapter.ts+│ │ └── baileys.adapter.spec.ts+│ └── identity/+│ ├── wa-id.ts+│ └── wa-id.spec.ts+└── modules/+ ├── session/+ │ ├── session.service.ts+ │ └── session.service.spec.ts+ └── webhook/+ ├── webhook.service.ts+ └── webhook.service.spec.ts```-### Mocking Guidelines+### What Unit Tests Should Cover-```typescript-// Mock WhatsApp Engine-const mockEngine = {- initialize: jest.fn().mockResolvedValue(undefined),- sendMessage: jest.fn().mockResolvedValue({ messageId: 'msg_123' }),- getContacts: jest.fn().mockResolvedValue([]),- disconnect: jest.fn(),- on: jest.fn(),-};--// Mock Repository-const mockRepository = {- findById: jest.fn(),- findByName: jest.fn(),- save: jest.fn(),- update: jest.fn(),- delete: jest.fn(),-};--// Mock HTTP Service (for webhooks)-const mockHttpService = {- post: jest.fn().mockReturnValue(of({ data: {}, status: 200 })),-};-```+- Service behavior, validation, and error mapping.+- Engine adapter mapping at the boundary, especially neutral WhatsApp IDs and delivery statuses.+- Security helpers such as SSRF checks, path containment, trusted proxy IP resolution, and secret-file handling.+- Database migrations for SQLite and PostgreSQL where SQL differs.+- Plugin hooks, plugin loading, and capability wrappers.+- Race-prone behavior such as reconnect handling, ack reconciliation, and concurrent reaction updates.-## 09.3 Integration Testing--### Test Database--```yaml-# docker-compose.test.yml-version: '3.8'-services:- postgres-test:- image: postgres:15- environment:- POSTGRES_DB: openwa_test- POSTGRES_USER: test- POSTGRES_PASSWORD: test- ports:- - "5433:5432"- tmpfs:- - /var/lib/postgresql/data-- redis-test:- image: redis:7-alpine- ports:- - "6380:6379"-```+### Unit Test Pattern-### Integration Test Examples+Use Nest's testing module when dependency injection behavior matters. For pure functions and small helpers,+prefer direct imports with focused assertions.```typescript-// session.integration.spec.ts-describe('Session Integration', () => {- let app: INestApplication;- let dataSource: DataSource;-- beforeAll(async () => {- const module = await Test.createTestingModule({- imports: [AppModule],- })- .overrideProvider(EngineFactory)- .useValue(mockEngineFactory)- .compile();-- app = module.createNestApplication();- await app.init();- dataSource = module.get(DataSource);- });-- afterAll(async () => {- await dataSource.destroy();- await app.close();- });-- beforeEach(async () => {- // Clean database before each test- await dataSource.query('TRUNCATE TABLE sessions CASCADE');- });-- describe('POST /api/sessions', () => {- it('should create session and return QR code', async () => {- const response = await request(app.getHttpServer())- .post('/api/sessions')- .set('X-API-Key', 'test-api-key')- .send({ name: 'integration-test' })- .expect(201);-- expect(response.body.status).toBe('SCAN_QR');- expect(response.body.qr).toBeDefined();- });-- it('should reject duplicate session name', async () => {- // Create first session- await request(app.getHttpServer())- .post('/api/sessions')- .set('X-API-Key', 'test-api-key')- .send({ name: 'duplicate-test' })- .expect(201);-- // Try to create duplicate- const response = await request(app.getHttpServer())- .post('/api/sessions')- .set('X-API-Key', 'test-api-key')- .send({ name: 'duplicate-test' })- .expect(409);-- expect(response.body.statusCode).toBe(409);- expect(response.body.message).toMatch(/SESSION_ALREADY_EXISTS/i);- });- });-- describe('Webhook Delivery', () => {- it('should deliver webhook on message received', async () => {- // Setup webhook endpoint mock- const webhookServer = await createMockWebhookServer(3001);-- // Create session with webhook- await request(app.getHttpServer())- .post('/api/sessions')- .set('X-API-Key', 'test-api-key')- .send({- name: 'webhook-test',- webhook: {- url: 'http://localhost:3001/webhook',- events: ['message.received']- }- });-- // Simulate incoming message- await simulateIncomingMessage(app, 'webhook-test', {- chatId: '[email protected]',- text: 'Test message'- });-- // Verify webhook was called- expect(webhookServer.receivedPayloads).toHaveLength(1);- expect(webhookServer.receivedPayloads[0].event).toBe('message.received');-- await webhookServer.close();- });+describe('resolveReconnectConfig', () => {+ it('clamps invalid reconnect settings to safe defaults', () => {+ expect(+ resolveReconnectConfig({+ maxReconnectAttempts: 'not-a-number',+ reconnectBaseDelay: -1,+ }),+ ).toEqual({ maxAttempts: 5, baseDelay: 1000 });});});```-## 09.4 E2E Testing--### Critical User Journeys--```mermaid-flowchart LR- subgraph Journey1["Session Lifecycle"]- J1A[Create Session] --> J1B[Scan QR]- J1B --> J1C[Verify Connected]- J1C --> J1D[Logout]- end-- subgraph Journey2["Messaging Flow"]- J2A[Get Session] --> J2B[Send Text]- J2B --> J2C[Verify Sent]- J2C --> J2D[Check Webhook]- end-- subgraph Journey3["Bulk Operations"]- J3A[Create Batch] --> J3B[Monitor Progress]- J3B --> J3C[Verify Results]- end-```+## 09.4 E2E Smoke Tests-### E2E Test Scenarios+E2E smoke tests live in `test/` and use `test/jest-e2e.json`.-| ID | Scenario | Steps | Expected Result |-|----|----------|-------|-----------------|-| E2E-001 | Session Creation | Create → Get QR → Verify status | Status = SCAN_QR |-| E2E-002 | Send Text Message | Send text → Check response → Verify webhook | Message delivered + webhook called |-| E2E-003 | Send Media | Send image → Check upload → Verify delivery | Media delivered |-| E2E-004 | Bulk Messaging | Create batch → Monitor → Verify all sent | 100% delivery |-| E2E-005 | Webhook Retry | Setup failing webhook → Verify 3 retries | 3 attempts logged |-| E2E-006 | Rate Limiting | Exceed rate limit → Check 429 response | Proper error + headers |-| E2E-007 | API Key Auth | Invalid key → Valid key → Permission check | Proper auth flow |-| E2E-008 | WebSocket Events | Connect → Subscribe → Receive event | Event delivered |+```text+test/+├── app.e2e-spec.ts+├── baileys-engine.e2e-spec.ts+├── serve-static.e2e-spec.ts+├── jest-e2e.json+└── setup-e2e.ts+```-### E2E Test Implementation+`test/setup-e2e.ts` configures the app for local test boot before `AppModule` is imported:-```typescript-// e2e/session.e2e-spec.ts-describe('Session E2E', () => {- let api: AxiosInstance;-- beforeAll(() => {- api = axios.create({- baseURL: process.env.TEST_API_URL || 'http://localhost:2785/api',- headers: { 'X-API-Key': process.env.TEST_API_KEY }- });- });+- `NODE_ENV=test`+- SQLite database+- queue disabled+- auto-start sessions disabled+- schema synchronize enabled for test boot- describe('Complete Session Lifecycle', () => {- let sessionId: string;+The e2e suite intentionally avoids requiring a live WhatsApp account. It focuses on application boot,+authentication plumbing, public health endpoints, engine selection paths, and dashboard static serving behavior.- it('Step 1: Create new session', async () => {- const response = await api.post('/sessions', {- name: `e2e-test-${Date.now()}`- });+## 09.5 Coverage Policy- expect(response.status).toBe(201);- expect(response.data.status).toBe('SCAN_QR');- sessionId = response.data.id;- });+Coverage thresholds are defined in `package.json` under the Jest configuration. Current policy:- it('Step 2: Get QR code', async () => {- const response = await api.get(`/sessions/${sessionId}/qr`);+| Scope | Branches | Functions | Lines | Statements |+|-------|----------|-----------|-------|------------|+| Global | 30% | 30% | 33% | 33% |+| `src/common/security/` | 85% | 95% | 90% | 90% |+| `src/modules/auth/` | 30% | 50% | 45% | 45% |- expect(response.status).toBe(200);- expect(response.data.image).toMatch(/^data:image\/png;base64,/);- });+These thresholds are intentionally higher for security-sensitive code. When adding security code,+add focused regression tests instead of relying on broad integration coverage.- it('Step 3: Check session status', async () => {- const response = await api.get(`/sessions/${sessionId}`);+## 09.6 CI Checks- expect(response.status).toBe(200);- expect(response.data.id).toBe(sessionId);- });+CI is defined in `.github/workflows/ci.yml`.- it('Step 4: Delete session', async () => {- const response = await api.delete(`/sessions/${sessionId}`);+| Job | Checks |+|-----|--------|+| `lint` | `npm audit --audit-level=critical`, backend ESLint, formatting check |+| `test` | backend coverage run, e2e smoke tests, Codecov upload |+| `dashboard` | dashboard install, lint, i18n parity, build |+| `build` | backend build after lint/test/dashboard jobs pass |+| `docker` | multi-arch Docker build and push on branch pushes |- expect(response.status).toBe(200);- });+Release tags run `.github/workflows/release.yml`, which gates release and Docker publishing behind tests+and build.- it('Step 5: Verify session deleted', async () => {- try {- await api.get(`/sessions/${sessionId}`);- fail('Should have thrown 404');- } catch (error) {- expect(error.response.status).toBe(404);- }- });- });-});-```+## 09.7 Testing Guidelines-## 09.5 Performance Testing+### Add Tests Near the Risk-### Tools+For narrow changes, add or update the nearest `*.spec.ts`. For shared behavior, test both the helper and+one representative consumer. For adapter changes, test the adapter boundary shape rather than the external+WhatsApp library itself.-- **k6** - Load testing-- **Artillery** - API stress testing+### Mock External Systems-### Performance Test Scenarios+Do not require live WhatsApp, Redis, S3, Docker, or internet access for the default test suite. Use mocks,+temporary directories, or local in-memory objects. Keep live-service tests opt-in and document their+environment variables separately.-```javascript-// k6/load-test.js-import http from 'k6/http';-import { check, sleep } from 'k6';+### Preserve Engine-Neutral Contracts-export const options = {- stages: [- { duration: '30s', target: 20 }, // Ramp up- { duration: '1m', target: 50 }, // Stay at 50 users- { duration: '30s', target: 100 }, // Peak load- { duration: '30s', target: 0 }, // Ramp down- ],- thresholds: {- http_req_duration: ['p(95)<500'], // 95% requests under 500ms- http_req_failed: ['rate<0.01'], // Less than 1% errors- },-};+Tests that touch WhatsApp IDs should assert the neutral dialect used by application code:-const BASE_URL = __ENV.API_URL || 'http://localhost:2785/api';-const API_KEY = __ENV.API_KEY || 'test-key';+- `<phone>@c.us`+- `<id>@g.us`+- `<lid>@lid`+- `status@broadcast`, `<id>@newsletter`, `<id>@broadcast`-export default function () {- // Test: Get sessions- const sessionsRes = http.get(`${BASE_URL}/sessions`, {- headers: { 'X-API-Key': API_KEY },- });-- check(sessionsRes, {- 'status is 200': (r) => r.status === 200,- 'response time < 500ms': (r) => r.timings.duration < 500,- });+Application-level tests should not assert raw Baileys `@s.whatsapp.net` IDs or whatsapp-web.js internals.- sleep(1);+### Test Failure Paths- // Test: Send message (if session exists)- if (sessionsRes.json()?.length > 0) {- const sessionId = sessionsRes.json()[0].id;- const msgRes = http.post(- `${BASE_URL}/sessions/${sessionId}/messages/send-text`,- JSON.stringify({- chatId: '[email protected]',- text: `Load test message ${Date.now()}`- }),- {- headers: {- 'X-API-Key': API_KEY,- 'Content-Type': 'application/json'- }- }- );-- check(msgRes, {- 'message sent': (r) => r.status === 200 || r.status === 400,- 'response time < 2s': (r) => r.timings.duration < 2000,- });- }-- sleep(1);-}-```+For services that dispatch asynchronously, include tests for lookup failure, delivery failure, retries,+and swallowed fire-and-forget errors. A callback used with `void` should either catch internally or be+covered by a test proving it cannot leak an unhandled rejection.-### Performance Targets--| Metric | Target | Critical |-|--------|--------|----------|-| API Response Time (p95) | < 500ms | < 1000ms |-| Message Send Latency | < 2s | < 5s |-| QR Generation Time | < 3s | < 5s |-| Throughput | 100 req/s | 50 req/s |-| Memory per Session | < 500MB | < 800MB |-| Concurrent Sessions | 10+ | 5 |--## 09.6 Security Testing--### Checklist--```markdown-## Security Test Checklist--### Authentication-- [ ] API key required for all endpoints-- [ ] Invalid API key returns 401-- [ ] Expired API key rejected-- [ ] API key hash stored (not plain)--### Authorization-- [ ] Permission checks enforced-- [ ] Session isolation (can't access other sessions)-- [ ] IP whitelist working--### Input Validation-- [ ] SQL injection prevented-- [ ] XSS in webhook payloads prevented-- [ ] chatId format validated-- [ ] File upload size limits enforced--### Rate Limiting-- [ ] Rate limits working per endpoint-- [ ] Rate limit headers present-- [ ] 429 response on exceed--### Data Protection-- [ ] Sensitive data encrypted-- [ ] No secrets in logs-- [ ] Session auth state encrypted-```+### Keep E2E Fast-### Security Test Examples+E2E tests should stay smoke-level unless a change specifically needs a full app boot. Prefer unit tests+for business logic and e2e tests for wiring, guards, global pipes, app boot, and route-level behavior.-```typescript-// security.spec.ts-describe('Security Tests', () => {- describe('Authentication', () => {- it('should reject request without API key', async () => {- const response = await request(app.getHttpServer())- .get('/api/sessions')- .expect(401);-- expect(response.body.statusCode).toBe(401);- expect(response.body.message).toBeDefined();- });-- it('should reject invalid API key', async () => {- const response = await request(app.getHttpServer())- .get('/api/sessions')- .set('X-API-Key', 'invalid-key')- .expect(401);-- expect(response.body.statusCode).toBe(401);- expect(response.body.message).toBeDefined();- });- });+## 09.8 Manual Smoke Checks- describe('Input Validation', () => {- it('should reject SQL injection in session name', async () => {- const response = await request(app.getHttpServer())- .post('/api/sessions')- .set('X-API-Key', validApiKey)- .send({ name: "'; DROP TABLE sessions; --" })- .expect(400);-- expect(response.body.statusCode).toBe(400);- expect(response.body.message).toBeDefined();- });-- it('should reject XSS in webhook URL', async () => {- const response = await request(app.getHttpServer())- .post('/api/sessions/sess_123/webhooks')- .set('X-API-Key', validApiKey)- .send({- url: 'javascript:alert(1)',- events: ['message.received']- })- .expect(400);-- expect(response.body.statusCode).toBe(400);- expect(response.body.message).toBeDefined();- });- });+Use these checks when changing Docker, Chromium, dashboard serving, or session startup behavior.- describe('Rate Limiting', () => {- it('should block after exceeding rate limit', async () => {- // Send 35 requests (limit is 30)- for (let i = 0; i < 35; i++) {- await request(app.getHttpServer())- .get('/api/sessions')- .set('X-API-Key', validApiKey);- }-- const response = await request(app.getHttpServer())- .get('/api/sessions')- .set('X-API-Key', validApiKey)- .expect(429);-- expect(response.headers['retry-after']).toBeDefined();- });- });-});+```bash+npm run build:all+node dist/main```-## 09.7 CI/CD Integration--### GitHub Actions Workflow--```yaml-# .github/workflows/test.yml-name: Tests--on:- push:- branches: [main, develop]- pull_request:- branches: [main]--jobs:- unit-tests:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4- - uses: actions/setup-node@v4- with:- node-version: '22'- cache: 'npm'-- - run: npm ci- - run: npm run test:cov-- - name: Upload coverage- uses: codecov/codecov-action@v3- with:- files: ./coverage/lcov.info-- integration-tests:- runs-on: ubuntu-latest- services:- postgres:- image: postgres:15- env:- POSTGRES_DB: openwa_test- POSTGRES_USER: test- POSTGRES_PASSWORD: test- ports:- - 5432:5432- redis:- image: redis:7- ports:- - 6379:6379-- steps:- - uses: actions/checkout@v4- - uses: actions/setup-node@v4- with:- node-version: '22'-- - run: npm ci- - run: npm run test:integration- env:- DATABASE_URL: postgresql://test:test@localhost:5432/openwa_test- REDIS_URL: redis://localhost:6379-- e2e-tests:- runs-on: ubuntu-latest- needs: [unit-tests, integration-tests]- steps:- - uses: actions/checkout@v4- - uses: actions/setup-node@v4- with:- node-version: '22'-- - run: npm ci- - run: npm run build- - run: npm run test:e2e-- security-scan:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4- - run: npm audit --audit-level=high- - uses: snyk/actions/node@master- env:- SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}+```bash+docker compose -f docker-compose.dev.yml up -d --build+curl -f http://localhost:2785/api/health/ready```-## 09.8 Test Reporting--### Coverage Requirements+For production-compose changes:-| Area | Minimum Coverage |-|------|------------------|-| Services | 85% |-| Controllers | 80% |-| Guards | 90% |-| Utils | 95% |-| Overall | 80% |--### Test Report Template--```markdown-## Test Execution Report--**Date:** YYYY-MM-DD-**Version:** X.X.X-**Environment:** CI / Staging / Production--### Summary--| Type | Total | Passed | Failed | Skipped |-|------|-------|--------|--------|---------|-| Unit | 150 | 148 | 2 | 0 |-| Integration | 45 | 45 | 0 | 0 |-| E2E | 15 | 14 | 1 | 0 |+```bash+docker compose up -d --build+docker compose logs -f openwa-api+```-### Coverage+Live WhatsApp checks require an operator-owned account and should not be part of CI:-| Module | Lines | Functions | Branches |-|--------|-------|-----------|----------|-| session | 92% | 95% | 88% |-| message | 85% | 90% | 82% |-| webhook | 88% | 92% | 85% |-| **Total** | **87%** | **91%** | **84%** |+1. Create a session.+2. Start the session.+3. Scan QR or request a pairing code.+4. Confirm session reaches `ready`.+5. Send a text message to a test chat.+6. Confirm message history, webhook delivery, and WebSocket events.-### Failed Tests+## 09.9 Known Gaps-1. `message.service.spec.ts` - sendMedia timeout- - **Cause:** Mock timeout misconfigured- - **Action:** Fix in PR #123+- No default CI job exercises a real WhatsApp connection.+- No default CI job exercises real PostgreSQL, Redis, S3/MinIO, or Docker socket proxy integration.+- Performance testing is not automated.+- Dashboard UI tests are not currently automated beyond lint, i18n parity, and build.-### Performance Results+These gaps are intentional for the default suite because the project prioritizes deterministic tests that+run without external services. Add opt-in integration jobs only when they are isolated, documented, and do+not make normal contributor workflows brittle.-| Test | Target | Actual | Status |-|------|--------|--------|--------|-| API p95 latency | <500ms | 320ms | ✅ |-| Throughput | 100 req/s | 125 req/s | ✅ |-```---<div align="center">