|
| 1 | +import * as path from 'path'; |
| 2 | +import { Project, ClassDeclaration, SourceFile } from 'ts-morph'; |
| 3 | +import { SwaggerParser } from '../../../core/parser.js'; |
| 4 | +import { GeneratorConfig, PathInfo } from '../../../core/types.js'; |
| 5 | +import { |
| 6 | + camelCase, |
| 7 | + pascalCase, |
| 8 | + getBasePathTokenName, |
| 9 | + isDataTypeInterface, |
| 10 | + getTypeScriptType, |
| 11 | +} from '../../../core/utils.js'; |
| 12 | +import { MockDataGenerator } from './mock-data.generator.js'; |
| 13 | + |
| 14 | +export class ServiceTestGenerator { |
| 15 | + private mockDataGenerator: MockDataGenerator; |
| 16 | + |
| 17 | + constructor( |
| 18 | + private readonly parser: SwaggerParser, |
| 19 | + private readonly project: Project, |
| 20 | + private readonly config: GeneratorConfig, |
| 21 | + ) { |
| 22 | + this.mockDataGenerator = new MockDataGenerator(parser); |
| 23 | + } |
| 24 | + |
| 25 | + public generateServiceTestFile(controllerName: string, operations: PathInfo[], outputDir: string): void { |
| 26 | + const serviceName = `${pascalCase(controllerName)}Service`; |
| 27 | + const testFileName = `${camelCase(controllerName)}.service.spec.ts`; |
| 28 | + const testFilePath = path.join(outputDir, testFileName); |
| 29 | + |
| 30 | + const sourceFile = this.project.createSourceFile(testFilePath, '', { overwrite: true }); |
| 31 | + |
| 32 | + const modelImports = this.collectModelImports(operations); |
| 33 | + this.addImports(sourceFile, serviceName, Array.from(modelImports)); |
| 34 | + |
| 35 | + sourceFile.addStatements([ |
| 36 | + `describe('${serviceName}', () => {`, |
| 37 | + ` let service: ${serviceName};`, |
| 38 | + ` let httpMock: HttpTestingController;`, |
| 39 | + '', |
| 40 | + ` beforeEach(() => {`, |
| 41 | + ` TestBed.configureTestingModule({`, |
| 42 | + ` imports: [HttpClientTestingModule],`, |
| 43 | + ` providers: [`, |
| 44 | + ` ${serviceName},`, |
| 45 | + ` { provide: ${getBasePathTokenName(this.config.clientName)}, useValue: '/api/v1' }`, |
| 46 | + ` ]`, |
| 47 | + ` });`, |
| 48 | + ` service = TestBed.inject(${serviceName});`, |
| 49 | + ` httpMock = TestBed.inject(HttpTestingController);`, |
| 50 | + ` });`, |
| 51 | + '', |
| 52 | + ` afterEach(() => {`, |
| 53 | + ` httpMock.verify();`, |
| 54 | + ` });`, |
| 55 | + '', |
| 56 | + ` it('should be created', () => {`, |
| 57 | + ` expect(service).toBeTruthy();`, |
| 58 | + ` });`, |
| 59 | + ...this.generateMethodTests(operations), |
| 60 | + `});`, |
| 61 | + ]); |
| 62 | + |
| 63 | + sourceFile.formatText(); |
| 64 | + } |
| 65 | + |
| 66 | + private generateMethodTests(operations: PathInfo[]): string[] { |
| 67 | + const tests: string[] = []; |
| 68 | + for (const op of operations) { |
| 69 | + if (!op.methodName) continue; |
| 70 | + |
| 71 | + const { responseModel, responseType, bodyModel } = this.getMethodTypes(op); |
| 72 | + const params = op.parameters?.map(p => ({ |
| 73 | + name: camelCase(p.name), |
| 74 | + value: typeof p.schema?.type === 'number' ? '123' : `'test-${p.name}'`, |
| 75 | + })) ?? []; |
| 76 | + const bodyParam = op.requestBody?.content?.['application/json'] |
| 77 | + ? { name: bodyModel ? camelCase(bodyModel) : 'body', model: bodyModel } |
| 78 | + : null; |
| 79 | + |
| 80 | + const allArgs = [ |
| 81 | + ...params.map(p => p.name), |
| 82 | + ...(bodyParam ? [bodyParam.name] : []) |
| 83 | + ]; |
| 84 | + |
| 85 | + tests.push(`\n describe('${op.methodName}()', () => {`); |
| 86 | + |
| 87 | + // Happy Path Test |
| 88 | + tests.push(` it('should return ${responseType} on success', () => {`); |
| 89 | + if (responseModel) { |
| 90 | + const mockResponse = this.mockDataGenerator.generate(responseModel); |
| 91 | + tests.push(` const mockResponse: ${responseModel} = ${mockResponse};`); |
| 92 | + } else { |
| 93 | + tests.push(` const mockResponse = null;`); |
| 94 | + } |
| 95 | + if (bodyParam?.model) { |
| 96 | + const mockBody = this.mockDataGenerator.generate(bodyParam.model); |
| 97 | + tests.push(` const ${bodyParam.name}: ${bodyParam.model} = ${mockBody};`); |
| 98 | + } else if (bodyParam) { |
| 99 | + tests.push(` const ${bodyParam.name} = 'test-body';`); |
| 100 | + } |
| 101 | + |
| 102 | + params.forEach(p => tests.push(` const ${p.name} = ${p.value};`)); |
| 103 | + |
| 104 | + tests.push(` service.${op.methodName}(${allArgs.join(', ')}).subscribe(response => {`); |
| 105 | + tests.push(` expect(response).toEqual(mockResponse);`); |
| 106 | + tests.push(` });`); |
| 107 | + |
| 108 | + const url = op.path.replace(/{(\w+)}/g, (_, paramName) => `\${${camelCase(paramName)}}`); |
| 109 | + tests.push(` const req = httpMock.expectOne(\`/api/v1${url}\`);`); |
| 110 | + tests.push(` expect(req.request.method).toBe('${op.method}');`); |
| 111 | + |
| 112 | + if (bodyParam) { |
| 113 | + tests.push(` expect(req.request.body).toEqual(${bodyParam.name});`); |
| 114 | + } |
| 115 | + |
| 116 | + tests.push(` req.flush(mockResponse);`); |
| 117 | + tests.push(` });`); |
| 118 | + |
| 119 | + // Error Path Test |
| 120 | + tests.push(` it('should handle a 404 error', () => {`); |
| 121 | + if (bodyParam?.model) { |
| 122 | + const mockBody = this.mockDataGenerator.generate(bodyParam.model); |
| 123 | + tests.push(` const ${bodyParam.name}: ${bodyParam.model} = ${mockBody};`); |
| 124 | + } else if (bodyParam) { |
| 125 | + tests.push(` const ${bodyParam.name} = 'test-body';`); |
| 126 | + } |
| 127 | + params.forEach(p => tests.push(` const ${p.name} = ${p.value};`)); |
| 128 | + |
| 129 | + tests.push(` service.${op.methodName}(${allArgs.join(', ')}).subscribe({`); |
| 130 | + tests.push(` next: () => fail('should have failed with a 404 error'),`); |
| 131 | + tests.push(` error: (error) => {`); |
| 132 | + tests.push(` expect(error.status).toBe(404);`); |
| 133 | + tests.push(` }`); |
| 134 | + tests.push(` });`); |
| 135 | + |
| 136 | + tests.push(` const req = httpMock.expectOne(\`/api/v1${url}\`);`); |
| 137 | + tests.push(` req.flush('Not Found', { status: 404, statusText: 'Not Found' });`); |
| 138 | + tests.push(` });`); |
| 139 | + |
| 140 | + tests.push(` });`); |
| 141 | + } |
| 142 | + return tests; |
| 143 | + } |
| 144 | + |
| 145 | + private addImports(sourceFile: SourceFile, serviceName: string, modelImports: string[]): void { |
| 146 | + sourceFile.addImportDeclarations([ |
| 147 | + { moduleSpecifier: '@angular/core/testing', namedImports: ['TestBed'] }, |
| 148 | + { moduleSpecifier: '@angular/common/http/testing', namedImports: ['HttpClientTestingModule', 'HttpTestingController'] }, |
| 149 | + { moduleSpecifier: `./${camelCase(serviceName.replace(/Service$/, ''))}.service`, namedImports: [serviceName] }, |
| 150 | + { moduleSpecifier: `../models`, namedImports: modelImports.length > 0 ? modelImports : [] }, |
| 151 | + { moduleSpecifier: '../tokens', namedImports: [getBasePathTokenName(this.config.clientName)] }, |
| 152 | + ]); |
| 153 | + } |
| 154 | + |
| 155 | + private getMethodTypes(op: PathInfo): { responseModel?: string, responseType: string, bodyModel?: string } { |
| 156 | + const knownTypes = this.parser.schemas.map(s => s.name); |
| 157 | + const successResponseSchema = op.responses?.['200']?.content?.['application/json']?.schema; |
| 158 | + const responseType = successResponseSchema ? getTypeScriptType(successResponseSchema as any, this.config, knownTypes) : 'any'; |
| 159 | + const responseModel = isDataTypeInterface(responseType.replace(/\[\]| \| null/g, '')) ? responseType.replace(/\[\]| \| null/g, '') : undefined; |
| 160 | + |
| 161 | + const requestBodySchema = op.requestBody?.content?.['application/json']?.schema; |
| 162 | + const bodyType = requestBodySchema ? getTypeScriptType(requestBodySchema as any, this.config, knownTypes) : 'any'; |
| 163 | + const bodyModel = isDataTypeInterface(bodyType.replace(/\[\]| \| null/g, '')) ? bodyType.replace(/\[\]| \| null/g, '') : undefined; |
| 164 | + |
| 165 | + return { responseModel, responseType, bodyModel }; |
| 166 | + } |
| 167 | + |
| 168 | + private collectModelImports(operations: PathInfo[]): Set<string> { |
| 169 | + const modelImports = new Set<string>(); |
| 170 | + for (const op of operations) { |
| 171 | + const { responseModel, bodyModel } = this.getMethodTypes(op); |
| 172 | + if (responseModel) modelImports.add(responseModel); |
| 173 | + if (bodyModel) modelImports.add(bodyModel); |
| 174 | + |
| 175 | + (op.parameters ?? []).forEach(param => { |
| 176 | + const schemaObject = param.schema ? param.schema : param; |
| 177 | + const paramType = getTypeScriptType(schemaObject as any, this.config, this.parser.schemas.map(s => s.name)).replace(/\[\]| \| null/g, ''); |
| 178 | + if (isDataTypeInterface(paramType)) { |
| 179 | + modelImports.add(paramType); |
| 180 | + } |
| 181 | + }); |
| 182 | + } |
| 183 | + return modelImports; |
| 184 | + } |
| 185 | +} |
0 commit comments