diff options
| author | ST-DDT <[email protected]> | 2023-01-23 18:47:09 +0100 |
|---|---|---|
| committer | GitHub <[email protected]> | 2023-01-23 17:47:09 +0000 |
| commit | 23aa08800ac66a5b16e405d04d07ea538d16dd6b (patch) | |
| tree | d031ddeff74354b9064b4b32ceb5f5e2bf5f0ac4 /test/scripts | |
| parent | 826cb0b2db247fde4d0ee93933dfecd4f3a656dd (diff) | |
| download | faker-23aa08800ac66a5b16e405d04d07ea538d16dd6b.tar.xz faker-23aa08800ac66a5b16e405d04d07ea538d16dd6b.zip | |
refactor: reorganize apidoc scripts and reuse them for tests (#1759)
Diffstat (limited to 'test/scripts')
| -rw-r--r-- | test/scripts/apidoc/examplesAndDeprecations.spec.ts | 146 | ||||
| -rw-r--r-- | test/scripts/apidoc/signature.debug.ts | 2 | ||||
| -rw-r--r-- | test/scripts/apidoc/signature.spec.ts | 8 | ||||
| -rw-r--r-- | test/scripts/apidoc/utils.ts | 58 |
4 files changed, 101 insertions, 113 deletions
diff --git a/test/scripts/apidoc/examplesAndDeprecations.spec.ts b/test/scripts/apidoc/examplesAndDeprecations.spec.ts index df1769b4..ac73244c 100644 --- a/test/scripts/apidoc/examplesAndDeprecations.spec.ts +++ b/test/scripts/apidoc/examplesAndDeprecations.spec.ts @@ -1,7 +1,5 @@ import { mkdirSync, writeFileSync } from 'node:fs'; import { resolve } from 'node:path'; -import type { DeclarationReflection, SignatureReflection } from 'typedoc'; -import { ReflectionKind } from 'typedoc'; import type { SpyInstance } from 'vitest'; import { afterAll, @@ -12,7 +10,6 @@ import { it, vi, } from 'vitest'; -import { selectApiModules } from '../../../scripts/apidoc/moduleMethods'; import { analyzeSignature, initMarkdownRenderer, @@ -23,9 +20,9 @@ import { extractSince, extractTagContent, isDeprecated, -} from '../../../scripts/apidoc/utils'; +} from '../../../scripts/apidoc/typedoc'; import { faker } from '../../../src'; -import { loadProject } from './utils'; +import { loadProjectModules } from './utils'; /* * This test ensures, that every method @@ -42,17 +39,7 @@ const locales: Record<string, string> = { beforeAll(initMarkdownRenderer); describe('examples and deprecations', () => { - const project = loadProject(); - - const modules: Record<string, DeclarationReflection[]> = selectApiModules( - project - ).reduce( - (a, v) => ({ - ...a, - [v.name]: v.getChildrenByKind(ReflectionKind.Method), - }), - {} - ); + const modules = loadProjectModules(); const consoleSpies: Array<SpyInstance> = Object.keys(console) .filter((key) => typeof console[key] === 'function') @@ -65,12 +52,7 @@ describe('examples and deprecations', () => { } }); - describe.each(Object.entries(modules))('%s', (moduleName, methods) => { - const methodsByName: Record<string, DeclarationReflection> = methods.reduce( - (a, v) => ({ ...a, [v.name]: v }), - {} - ); - + describe.each(Object.entries(modules))('%s', (moduleName, methodsByName) => { beforeEach(() => { faker.locale = 'en'; for (const spy of consoleSpies) { @@ -79,70 +61,74 @@ describe('examples and deprecations', () => { }); // eslint-disable-next-line @typescript-eslint/no-misused-promises - it.each(Object.entries(methodsByName))('%s', async (methodName, method) => { - const signatures: SignatureReflection[] = - method.signatures || method.type?.['declaration'].signatures; - const signature = signatures[signatures.length - 1]; - - // Extract examples and make them runnable - let examples = extractRawExamples(signature).join('').trim() ?? ''; - examples = examples.replace( - /faker([A-Z]{2})\./g, - (_, locale: string) => `faker.locale = '${locales[locale]}';\nfaker.` - ); - - expect(examples, `${moduleName}.${methodName} to have examples`).not.toBe( - '' - ); - - // Save examples to a file to run it - const dir = resolve(__dirname, 'temp', moduleName); - mkdirSync(dir, { recursive: true }); - const path = resolve(dir, `${methodName}.ts`); - writeFileSync( - path, - `import { faker } from '../../../../../src';\n${examples}` - ); - - // Run the examples - await import(path); + it.each(Object.entries(methodsByName))( + '%s', + async (methodName, signature) => { + // Extract examples and make them runnable + let examples = extractRawExamples(signature).join('').trim(); + examples = examples.replace( + /faker([A-Z]{2})\./g, + (_, locale: string) => `faker.locale = '${locales[locale]}';\nfaker.` + ); - // Verify logging - const deprecatedFlag = isDeprecated(signature); - if (deprecatedFlag) { - expect(consoleSpies[1]).toHaveBeenCalled(); expect( - extractTagContent('@deprecated', signature).join(''), - '@deprecated tag without message' + examples, + `${moduleName}.${methodName} to have examples` ).not.toBe(''); - } else { - for (const spy of consoleSpies) { - expect(spy).not.toHaveBeenCalled(); - } - } - // Verify @param tags - analyzeSignature(signature, moduleName, methodName).parameters.forEach( - (param) => { - const { name, description } = param; - const plainDescription = description.replace(/<[^>]+>/g, '').trim(); + // Save examples to a file to run it + const dir = resolve(__dirname, 'temp', moduleName); + mkdirSync(dir, { recursive: true }); + const path = resolve(dir, `${methodName}.ts`); + writeFileSync( + path, + `import { faker } from '../../../../../src';\n${examples}` + ); + + // Run the examples + await import(path); + + // Verify logging + const deprecatedFlag = isDeprecated(signature); + if (deprecatedFlag) { + expect(consoleSpies[1]).toHaveBeenCalled(); expect( - plainDescription, - `Expect param ${name} to have a description` - ).not.toBe('Missing'); - } - ); - - // Verify @see tag - extractSeeAlsos(signature).forEach((link) => { - if (link.startsWith('faker.')) { - // Expected @see faker.xxx.yyy() - expect(link, 'Expect method reference to contain ()').toContain('('); - expect(link, 'Expect method reference to contain ()').toContain(')'); + extractTagContent('@deprecated', signature).join(''), + '@deprecated tag without message' + ).not.toBe(''); + } else { + for (const spy of consoleSpies) { + expect(spy).not.toHaveBeenCalled(); + } } - }); - expect(extractSince(signature), '@since to be present').toBeTruthy(); - }); + // Verify @param tags + analyzeSignature(signature, moduleName, methodName).parameters.forEach( + (param) => { + const { name, description } = param; + const plainDescription = description.replace(/<[^>]+>/g, '').trim(); + expect( + plainDescription, + `Expect param ${name} to have a description` + ).not.toBe('Missing'); + } + ); + + // Verify @see tag + extractSeeAlsos(signature).forEach((link) => { + if (link.startsWith('faker.')) { + // Expected @see faker.xxx.yyy() + expect(link, 'Expect method reference to contain ()').toContain( + '(' + ); + expect(link, 'Expect method reference to contain ()').toContain( + ')' + ); + } + }); + + expect(extractSince(signature), '@since to be present').toBeTruthy(); + } + ); }); }); diff --git a/test/scripts/apidoc/signature.debug.ts b/test/scripts/apidoc/signature.debug.ts index f805ca54..6be0e49f 100644 --- a/test/scripts/apidoc/signature.debug.ts +++ b/test/scripts/apidoc/signature.debug.ts @@ -16,7 +16,7 @@ initMarkdownRenderer() .then(() => { Object.entries(methods).forEach(([name, method]) => { console.log('Analyzing: ', name); - const result = analyzeSignature(method.signatures[0], null, method.name); + const result = analyzeSignature(method, null, method.name); console.log('Result: ', result); }); }) diff --git a/test/scripts/apidoc/signature.spec.ts b/test/scripts/apidoc/signature.spec.ts index 43ab00e7..d90370a2 100644 --- a/test/scripts/apidoc/signature.spec.ts +++ b/test/scripts/apidoc/signature.spec.ts @@ -19,13 +19,11 @@ describe('signature', () => { }); it('expected and actual methods are equal', () => { - expect(Object.keys(methods).sort()).toMatchSnapshot(); + expect(Object.keys(methods)).toMatchSnapshot(); }); - it.each(Object.keys(methods).sort())('%s', (name) => { - const method = methods[name]; - expect(method, `Method ${name} to be defined`).toBeDefined(); - const actual = analyzeSignature(method.signatures[0], null, method.name); + it.each(Object.entries(methods))('%s', (name, signature) => { + const actual = analyzeSignature(signature, null, name); expect(actual).toMatchSnapshot(); }); diff --git a/test/scripts/apidoc/utils.ts b/test/scripts/apidoc/utils.ts index 19c4b4ea..61f3b848 100644 --- a/test/scripts/apidoc/utils.ts +++ b/test/scripts/apidoc/utils.ts @@ -1,43 +1,47 @@ -import type { DeclarationReflection, ProjectReflection } from 'typedoc'; -import { ReflectionKind } from 'typedoc'; -import { newTypeDocApp, patchProject } from '../../../scripts/apidoc/utils'; +import type { SignatureReflection, TypeDocOptions } from 'typedoc'; +import { + newTypeDocApp, + patchProject, + selectApiMethodSignatures, + selectApiModules, +} from '../../../scripts/apidoc/typedoc'; +import { mapByName } from '../../../scripts/apidoc/utils'; /** - * Loads the example methods using TypeDoc. + * Returns a record with the (Module-Name -> (Method-Name -> Method-Signature)) for the project. */ -export function loadExampleMethods(): Record<string, DeclarationReflection> { +export function loadProjectModules( + options: Partial<TypeDocOptions> = { + entryPoints: ['src/index.ts'], + }, + includeTestModules = false +): Record<string, Record<string, SignatureReflection>> { const app = newTypeDocApp(); - app.bootstrap({ - entryPoints: ['test/scripts/apidoc/signature.example.ts'], - tsconfig: 'test/scripts/apidoc/tsconfig.json', - }); + app.bootstrap(options); const project = app.convert(); + if (project == null) { + throw new Error('Failed to convert project'); + } + patchProject(project); - const methods: Record<string, DeclarationReflection> = project - .getChildrenByKind(ReflectionKind.Class)[0] - .getChildrenByKind(ReflectionKind.Method) - .reduce((a, v) => ({ ...a, [v.name]: v }), {}); + const modules = selectApiModules(project, includeTestModules); - return methods; + return mapByName(modules, selectApiMethodSignatures); } /** - * Loads the project using TypeDoc. + * Loads the example methods using TypeDoc. */ -export function loadProject(): ProjectReflection { - const app = newTypeDocApp(); - - app.bootstrap({ - entryPoints: ['src/index.ts'], - }); - - const project = app.convert(); - - patchProject(project); - - return project; +export function loadExampleMethods(): Record<string, SignatureReflection> { + return loadProjectModules( + { + entryPoints: ['test/scripts/apidoc/signature.example.ts'], + tsconfig: 'test/scripts/apidoc/tsconfig.json', + }, + true + )['SignatureTest']; } |
