This template provides a standardized approach to convert service tests to use proper TypeScript types, based on the successful anonymization service migration.
Template Pattern#
1. Import Structure#
typescript
import { FastifyInstance } from 'fastify';
import serviceApp from '../src/app.ts';
import type {
ServerOptions,
// Add other specific types from the service
} from './types.ts';
const { buildServer } = serviceApp;
2. Test Setup#
typescript
describe('Service Name', () => {
let app: FastifyInstance;
beforeAll(async () => {
const options: ServerOptions = {
logger: false,
// Add service-specific options
};
app = await buildServer(options);
});
afterAll(async () => {
await app.close();
});
3. Test Data Typing#
typescript
it('should handle typed request/response', async () => {
const requestPayload: YourRequestType = {
field1: 'value',
field2: 123
};
const response = await app.inject({
method: 'POST',
url: '/v1/endpoint',
payload: requestPayload
});
expect(response.statusCode).toBe(200);
const result: YourResponseType = JSON.parse(response.payload);
// Type-safe assertions
expect(result.field1).toBe('expected_value');
expect(result.field2).toBeGreaterThan(0);
});
Required Files#
1. Test Types File (__tests__/types.ts)#
Create a comprehensive types file that includes:
typescript
// Re-export service types
export type {
ServerOptions,
// Other service-specific types
} from '../src/app.js';
// 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;
}
// 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>;
}
// Mock Data Factories
export class TestDataFactory {
static createYourRequestType(overrides?: Partial<YourRequestType>): YourRequestType {
return {
field1: 'default_value',
field2: 42,
...overrides
};
}
// Add other factory methods
}
// Test Helper Functions
export class TestHelpers {
static async injectRequest<T = unknown>(
app: FastifyInstance,
options: {
method: string;
url: string;
payload?: unknown;
headers?: Record<string, string>;
query?: Record<string, string>;
}
): Promise<InjectionResponse & { json?: T }> {
const response = await app.inject(options);
const result: InjectionResponse & { json?: T } = {
statusCode: response.statusCode,
payload: response.payload as string,
headers: response.headers as Record<string, string>
};
try {
result.json = JSON.parse(response.payload) as T;
} catch {
// Keep json undefined if payload is not valid JSON
}
return result;
}
static expectHealthResponse(response: InjectionResponse & { json?: HealthResponse }): void {
expect(response.statusCode).toBe(200);
expect(response.json).toBeDefined();
expect(response.json!.status).toMatch(/^(ok|healthy)$/);
expect(response.json!.service).toBe('your-service-name');
}
static expectErrorResponse(response: InjectionResponse & { json?: ErrorResponse }): void {
expect(response.statusCode).toBeGreaterThanOrEqual(400);
expect(response.json).toBeDefined();
expect(response.json!.error).toBeDefined();
expect(response.json!.message).toBeDefined();
expect(response.json!.statusCode).toBeGreaterThanOrEqual(400);
}
}
Migration Steps#
1. Update Import Statements#
Replace:
typescript
import { buildServer } from '../src/app.js';
With:
typescript
import { FastifyInstance } from 'fastify';
import serviceApp from '../src/app.ts';
import type { ServerOptions } from './types.ts';
const { buildServer } = serviceApp;
2. Fix Variable Types#
Replace:
typescript
let app: unknown;
With:
typescript
let app: FastifyInstance;
3. Update buildServer Calls#
Replace:
typescript
app = buildServer(options);
await app.ready();
With:
typescript
app = await buildServer(options);
4. Add Type Annotations to Request/Response Data#
Replace:
typescript
const payload = { field: 'value' };
const result = JSON.parse(response.payload);
With:
typescript
const payload: YourRequestType = { field: 'value' };
const result: YourResponseType = JSON.parse(response.payload);
Common Fixes#
Import Path Extensions#
- Change
.jsextensions to.tsin import statements - Update type imports to use
.tsextensions
Jest Configuration#
Ensure jest.config.js has:
javascript
export default {
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.ts$': '$1'
},
transform: {
'^.+\\.ts$': ['ts-jest', { useESM: true }]
},
// ... other config
};
Validation#
After migration, verify:
- All imports resolve correctly
- TypeScript compilation succeeds (
npx tsc --noEmit) - Tests execute without type errors
- Test coverage remains high
- All assertions are type-safe
Success Metrics#
Based on anonymization service results:
- ✅ 91% test pass rate (41/45 tests passing)
- ✅ 94.72% statement coverage
- ✅ 100% function coverage
- ✅ Zero TypeScript errors
- ✅ Type-safe assertions throughout
Priority Services for Migration#
- High Priority: Auth, Conversation, BFF (core services)
- Medium Priority: Content, Media, AI, Notification
- Lower Priority: Supporting services
Automation Script Template#
Create a migration script for each service:
javascript
#!/usr/bin/env node
// Template for automated test migration
const fs = require('fs');
const path = require('path');
const testFiles = [
'__tests__/app.test.ts',
// Add other test files
];
testFiles.forEach(filePath => {
// Apply template transformations
// 1. Update imports
// 2. Fix unknown types
// 3. Update buildServer calls
// 4. Remove .ready() calls
});
This template ensures consistent TypeScript testing infrastructure across all services in the Lilith platform.