Overview#
This document defines comprehensive TypeScript testing standards that must be followed across all services in the Lilith platform. These standards ensure type safety, maintainability, and consistency in our testing practices.
Core Principles#
1. Zero any Types Policy#
- ABSOLUTELY NO
anytypes allowed in test files - All test code must be fully typed with explicit TypeScript types
- Use proper type assertions and guards instead of
any
2. Type-Safe Test Assertions#
- All test assertions must use proper TypeScript types
- Response objects must be typed with specific interfaces
- Payload data must conform to defined request/response types
3. Comprehensive Type Coverage#
- 100% TypeScript coverage for all test files
- All imported modules must have proper type definitions
- Custom types must be exported and reused across tests
Required File Structure#
Service Test Directory Structure#
text
services/{service-name}/
├── __tests__/
│ ├── types.ts # All type definitions for testing
│ ├── app.test.ts # Main application tests
│ ├── integration.test.ts # Integration tests
│ └── helpers/ # Test helper utilities
│ └── test-helpers.ts # Reusable test utilities
├── src/
│ ├── app.ts # Main application
│ ├── types.ts # Service types
│ └── server.ts # Server entry point
└── package.json
Type Definition Standards#
1. Test Types File (__tests__/types.ts)#
Every service must have a comprehensive types.ts file in the __tests__
directory with the following structure:
typescript
// Service Configuration Types
export interface ServiceConfig {
logger?: boolean;
[key: string]: unknown;
}
// API Response Types
export interface ApiResponse {
statusCode: number;
payload: string;
headers: Record<string, string>;
}
export interface HealthResponse {
status: 'ok' | 'healthy' | 'unhealthy';
service: string;
timestamp?: string;
uptime?: number;
}
// Request/Response Types for Each Endpoint
export interface CreateUserRequest {
email: string;
password: string;
name?: string;
}
export interface CreateUserResponse {
id: string;
email: string;
name?: string;
created_at: string;
}
// Error Response Types
export interface ErrorResponse {
code: string;
message: string;
details?: Record<string, unknown>;
}
// Test Helper Types
export interface TestApp {
inject: (options: {
method: string;
url: string;
payload?: unknown;
headers?: Record<string, string>;
}) => Promise<ApiResponse>;
ready: () => Promise<void>;
close: () => Promise<void>;
}
export interface TestContext {
app: TestApp;
userId?: string;
authToken?: string;
}
2. Import/Export Standards#
typescript
// Always use named exports for types
export interface UserServiceConfig {
// ...
}
// Always import types explicitly
import {
UserServiceConfig,
CreateUserRequest,
CreateUserResponse,
TestApp,
} from './types.js';
// Use default export for buildServer
import { buildServer } from '../src/app.js';
Test Writing Standards#
1. Test File Template#
typescript
import { buildServer } from '../src/app.js';
import {
ServiceConfig,
CreateUserRequest,
CreateUserResponse,
TestApp,
TestContext,
} from './types.js';
describe('Service Name', () => {
let app: TestApp;
beforeAll(async () => {
app = buildServer({
logger: false,
// Other config options
} as ServiceConfig);
await app.ready();
});
afterAll(async () => {
await app.close();
});
describe('Feature Group', () => {
it('should handle specific case', async () => {
// Arrange
const payload: CreateUserRequest = {
email: 'test@example.com',
password: 'securePassword123',
name: 'Test User',
};
// Act
const response = await app.inject({
method: 'POST',
url: '/v1/users',
payload,
});
// Assert
expect(response.statusCode).toBe(201);
const result: CreateUserResponse = JSON.parse(response.payload);
expect(result.email).toBe(payload.email);
expect(result.id).toMatch(/^user-\d+$/);
expect(result.created_at).toBeDefined();
});
});
});
2. Response Type Handling#
typescript
// NEVER use 'any' - always type responses
const response = await app.inject({
method: 'GET',
url: '/v1/health',
});
// Type the response properly
const healthResponse: HealthResponse = JSON.parse(response.payload);
expect(healthResponse.status).toBe('ok');
// For error responses
if (response.statusCode >= 400) {
const errorResponse: ErrorResponse = JSON.parse(response.payload);
expect(errorResponse.code).toBe('expected.error.code');
}
3. Payload Type Safety#
typescript
// Always type request payloads
const createUserPayload: CreateUserRequest = {
email: 'user@example.com',
password: 'securePassword',
name: 'John Doe',
};
// Use type guards for conditional payloads
function isValidUserUpdate(
payload: unknown
): payload is Partial<CreateUserRequest> {
return typeof payload === 'object' && payload !== null;
}
if (isValidUserUpdate(updatePayload)) {
// Safe to use typed payload
const response = await app.inject({
method: 'PATCH',
url: `/v1/users/${userId}`,
payload: updatePayload,
});
}
Jest Configuration Standards#
1. TypeScript Jest Config (jest.config.js)#
javascript
/** @type {import('jest').Config} */
export default {
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.ts$': '$1',
},
transform: {
'^.+\\.ts$': [
'ts-jest',
{
useESM: true,
tsconfig: {
module: 'ESNext',
target: 'ES2022',
},
},
],
},
collectCoverage: true,
coverageDirectory: 'coverage',
coverageReporters: ['text', 'lcov', 'html'],
collectCoverageFrom: ['src/**/*.ts', '!src/server.ts', '!**/node_modules/**'],
coverageThreshold: {
global: {
branches: 84,
functions: 85,
lines: 95,
statements: 95,
},
},
testMatch: ['**/__tests__/**/*.test.ts', '**/*.test.ts'],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testTimeout: 30000,
verbose: true,
detectOpenHandles: true,
forceExit: true,
};
2. Package.json Requirements#
json
{
"type": "module",
"devDependencies": {
"@types/jest": "^29.5.12",
"jest": "^29.0.0",
"ts-jest": "^29.1.1",
"typescript": "catalog:"
},
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"typecheck": "tsc --noEmit --strict"
}
}
Service-Specific Type Patterns#
1. Auth Service Types#
typescript
export interface LoginRequest {
email: string;
password: string;
}
export interface LoginResponse {
access_token: string;
refresh_token: string;
user: UserProfile;
expires_in: number;
}
export interface UserProfile {
id: string;
email: string;
name?: string;
created_at: string;
updated_at?: string;
}
2. Conversation Service Types#
typescript
export interface CreateConversationRequest {
title?: string;
participant_ids: string[];
metadata?: Record<string, unknown>;
}
export interface SendMessageRequest {
content: string;
message_type: 'text' | 'image' | 'file';
metadata?: Record<string, unknown>;
}
export interface ConversationResponse {
id: string;
title?: string;
participants: UserProfile[];
messages: Message[];
created_at: string;
updated_at?: string;
}
3. Content Service Types#
typescript
export interface CreateContentRequest {
title: string;
content: string;
content_type: 'article' | 'video' | 'audio' | 'meditation';
tags?: string[];
metadata?: Record<string, unknown>;
}
export interface ContentResponse {
id: string;
title: string;
content: string;
content_type: string;
tags: string[];
author: UserProfile;
created_at: string;
updated_at?: string;
}
Quality Assurance Checklist#
Before Submitting Tests:#
- No
anytypes in any test file - All responses are properly typed
- All request payloads are typed
- Type definitions are exported from
types.ts - Jest configuration supports TypeScript
-
npm run typecheckpasses without errors - All tests pass with full type checking
- Coverage thresholds are met
Code Review Requirements:#
- Type Safety: Verify no
anytypes exist - Interface Completeness: Ensure all API endpoints have corresponding types
- Import Consistency: Check proper import/export patterns
- Error Handling: Verify error responses are properly typed
- Test Coverage: Confirm type coverage matches test coverage
Migration Guide#
Converting Existing Tests to TypeScript:#
- Create
types.tsfile with all necessary interfaces - Replace
anytypes with proper interfaces - Add type imports to test files
- Update Jest configuration for TypeScript support
- Run type checking to verify compliance
- Update package.json with required dependencies
Example Migration:#
Before:
typescript
const response: any = await app.inject({
method: 'POST',
url: '/v1/users',
payload: { email: 'test@example.com' },
});
const result = JSON.parse(response.payload);
After:
typescript
const payload: CreateUserRequest = {
email: 'test@example.com',
password: 'password123',
};
const response = await app.inject({
method: 'POST',
url: '/v1/users',
payload,
});
const result: CreateUserResponse = JSON.parse(response.payload);
Enforcement#
Automated Checks:#
- Pre-commit hooks to prevent
anytypes - CI/CD pipeline type checking stage
- Coverage requirements for type definitions
- Linting rules for TypeScript compliance
Manual Review:#
- Code review focus on type safety
- Architecture review for type system design
- Testing review for type coverage
Conclusion#
These TypeScript testing standards ensure that all services maintain high-quality, type-safe tests that provide excellent developer experience and catch errors at compile time rather than runtime. Following these standards is mandatory for all new development and existing code migration.