Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions fixtures/test-utils/advanced-types/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
export class TestUtilWrapper {
/**
* Generic return value
*/
findAll(): Array<HTMLElement> {
return [];
}

/**
* Generic arguments
*/
setAll(all: Array<HTMLElement>) {}

/**
* Method overload example
*/
keydown(keyCode: number): void;
keydown(keyboardEventProps: KeyboardEventInit): void;
keydown(args: KeyboardEventInit | number) {}
}

export default function createWrapper() {
return new TestUtilWrapper();
}
54 changes: 32 additions & 22 deletions src/test-utils-new/extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ function getDefaultValue(declaration: ts.Declaration) {
return declaration.initializer.getText();
}

export default function extractDocumentation(sourceFile: ts.SourceFile, checker: ts.TypeChecker): Array<TestUtilsDoc> {
export default function extractDocumentation(
sourceFile: ts.SourceFile,
checker: ts.TypeChecker,
extraExports: Array<string>
): Array<TestUtilsDoc> {
const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
if (!moduleSymbol) {
throw new Error(`Unable to resolve module: ${sourceFile.fileName}`);
Expand All @@ -35,14 +39,21 @@ export default function extractDocumentation(sourceFile: ts.SourceFile, checker:
const definitions: Array<TestUtilsDoc> = [];

for (const symbol of exportSymbols) {
const className = symbol.getName();
if (extraExports.includes(className)) {
continue;
}
if (!(symbol.flags & ts.SymbolFlags.Class)) {
throw new Error(`Exported symbol is not a class, got ${checker.symbolToString(symbol)}`);
}
const className = symbol.getName();

const classType = checker.getTypeAtLocation(extractDeclaration(symbol));
const classDefinition: TestUtilsDoc = { name: className, methods: [] };
for (const property of classType.getProperties()) {
const declaration = extractDeclaration(property);
const declaration = property.valueDeclaration;
if (!declaration) {
throw new Error(`Unexpected member on ${className} – ${property.getName()}`);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is not covered in tests. Because typescript says valueDeclaration could be undefined, but it always exists in our cases

}
const modifiers = (ts.canHaveModifiers(declaration) && ts.getModifiers(declaration)) || [];
if (
modifiers.find(
Expand All @@ -52,26 +63,25 @@ export default function extractDocumentation(sourceFile: ts.SourceFile, checker:
continue;
}
const type = checker.getTypeAtLocation(declaration);
if (type.getCallSignatures().length !== 1) {
throw new Error(`Unexpected member on ${className} – ${property.getName()}: ${stringifyType(type, checker)}`);
for (const signature of type.getCallSignatures()) {
// report each function signature as a separate method
classDefinition.methods.push({
name: property.getName(),
description: getDescription(property.getDocumentationComment(checker), declaration).text,
returnType: { name: stringifyType(signature.getReturnType(), checker) },
parameters: signature.parameters.map(parameter => {
const paramType = checker.getTypeAtLocation(extractDeclaration(parameter));
return {
name: parameter.name,
typeName: stringifyType(paramType, checker),
description: getDescription(parameter.getDocumentationComment(checker), declaration).text,
flags: { isOptional: isOptional(paramType) },
defaultValue: getDefaultValue(extractDeclaration(parameter)),
};
}),
inheritedFrom: getInheritedFrom(declaration, className),
Copy link
Member Author

@just-boris just-boris Jul 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed fields order to maintain compatibility with previous snapshot tests

});
}
const returnType = type.getCallSignatures()[0].getReturnType();
classDefinition.methods.push({
name: property.getName(),
description: getDescription(property.getDocumentationComment(checker), declaration).text,
inheritedFrom: getInheritedFrom(declaration, className),
parameters: type.getCallSignatures()[0].parameters.map(parameter => {
const paramType = checker.getTypeAtLocation(extractDeclaration(parameter));
return {
name: parameter.name,
typeName: stringifyType(paramType, checker),
description: getDescription(parameter.getDocumentationComment(checker), declaration).text,
flags: { isOptional: isOptional(paramType) },
defaultValue: getDefaultValue(extractDeclaration(parameter)),
};
}),
returnType: { name: stringifyType(returnType, checker) },
});
}
classDefinition.methods.sort((a, b) => a.name.localeCompare(b.name));

Expand Down
17 changes: 11 additions & 6 deletions src/test-utils-new/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@ import { bootstrapTypescriptProject } from '../bootstrap/typescript';
import extractDocumentation from './extractor';
import { TestUtilsDoc } from '../test-utils/interfaces';

export interface TestUtilsVariantOptions {
root: string;
extraExports?: Array<string>;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extra exports could be different for DOM and selectors code, this is why it is a separate config for each

}

export interface TestUtilsDocumenterOptions {
tsconfigPath: string;
domUtilsRoot: string;
selectorsUtilsRoot: string;
domUtils: TestUtilsVariantOptions;
selectorsUtils: TestUtilsVariantOptions;
}

interface TestUtilsDefinitions {
Expand All @@ -18,8 +23,8 @@ interface TestUtilsDefinitions {
}

export function documentTestUtilsNew(options: TestUtilsDocumenterOptions): TestUtilsDefinitions {
const domUtilsRoot = pathe.resolve(options.domUtilsRoot);
const selectorsUtilsRoot = pathe.resolve(options.selectorsUtilsRoot);
const domUtilsRoot = pathe.resolve(options.domUtils.root);
const selectorsUtilsRoot = pathe.resolve(options.selectorsUtils.root);
const program = bootstrapTypescriptProject(options.tsconfigPath);
const checker = program.getTypeChecker();

Expand All @@ -33,8 +38,8 @@ export function documentTestUtilsNew(options: TestUtilsDocumenterOptions): TestU
throw new Error(`File '${selectorsUtilsFile}' not found`);
}
return {
domDefinitions: extractDocumentation(domUtilsFile, checker),
selectorsDefinitions: extractDocumentation(selectorsUtilsFile, checker),
domDefinitions: extractDocumentation(domUtilsFile, checker, options.domUtils.extraExports ?? []),
selectorsDefinitions: extractDocumentation(selectorsUtilsFile, checker, options.selectorsUtils.extraExports ?? []),
};
}

Expand Down
69 changes: 63 additions & 6 deletions test/test-utils/__snapshots__/doc-generation.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,70 @@ exports[`Generate documentation > For simple cases 1`] = `
exports[`Generate documentation > deal with more complex types 1`] = `
[
{
"defaultValue": undefined,
"description": undefined,
"flags": {
"isOptional": false,
"description": "Generic return value",
"inheritedFrom": undefined,
"name": "findAll",
"parameters": [],
"returnType": {
"name": "Array<HTMLElement>",
},
},
{
"description": "Method overload example",
"inheritedFrom": undefined,
"name": "keydown",
"parameters": [
{
"defaultValue": undefined,
"description": undefined,
"flags": {
"isOptional": false,
},
"name": "keyCode",
"typeName": "number",
},
],
"returnType": {
"name": "void",
},
},
{
"description": "Method overload example",
"inheritedFrom": undefined,
"name": "keydown",
"parameters": [
{
"defaultValue": undefined,
"description": undefined,
"flags": {
"isOptional": false,
},
"name": "keyboardEventProps",
"typeName": "KeyboardEventInit",
},
],
"returnType": {
"name": "void",
},
},
{
"description": "Generic arguments",
"inheritedFrom": undefined,
"name": "setAll",
"parameters": [
{
"defaultValue": undefined,
"description": undefined,
"flags": {
"isOptional": false,
},
"name": "all",
"typeName": "Array<HTMLElement>",
},
],
"returnType": {
"name": "void",
},
"name": "all",
"typeName": "Array<HTMLElement>",
},
]
`;
19 changes: 3 additions & 16 deletions test/test-utils/doc-generation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,29 +49,16 @@ describe('Generate documentation', () => {
});

test('deal with more complex types', () => {
const results = buildTestUtilsProject('advanced-types');
const results = buildTestUtilsProject('advanced-types', { extraExports: ['default'] });

expect(results.length).toBe(1);
const classDoc = results[0];

expect(classDoc.name).toBe('TestUtilWrapper');

const methods = classDoc.methods;
expect(methods.length).toBe(2);

const findAllMethod = methods.find(method => method.name === 'findAll');
expect(findAllMethod).toBeDefined();
expect(findAllMethod?.returnType).toEqual({ name: 'Array<HTMLElement>' });
expect(findAllMethod?.parameters).toEqual([]);
expect(findAllMethod?.description).toBeUndefined();
expect(findAllMethod?.inheritedFrom).toBeUndefined();

const setAllMethod = methods.find(method => method.name === 'setAll');
expect(setAllMethod).toBeDefined();
expect(setAllMethod?.returnType).toEqual({ name: 'void' });
expect(setAllMethod?.parameters).toMatchSnapshot();
expect(setAllMethod?.description).toBeUndefined();
expect(setAllMethod?.inheritedFrom).toBeUndefined();
expect(methods.length).toBe(4);
expect(methods).toMatchSnapshot();
});

test('and deal with inheritance', () => {
Expand Down
9 changes: 4 additions & 5 deletions test/test-utils/test-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { documentTestUtilsNew, TestUtilsDocumenterOptions } from '../../src/test-utils-new';
import { documentTestUtilsNew, TestUtilsVariantOptions } from '../../src/test-utils-new';
import { TestUtilsDoc } from '../../src/test-utils/interfaces';

export function buildTestUtilsProject(
name: string,
configOverrides?: Partial<TestUtilsDocumenterOptions>
configOverrides?: Partial<TestUtilsVariantOptions>
): TestUtilsDoc[] {
return documentTestUtilsNew({
tsconfigPath: require.resolve(`../../fixtures/test-utils/${name}/tsconfig.json`),
domUtilsRoot: `fixtures/test-utils/${name}/index.ts`,
selectorsUtilsRoot: `fixtures/test-utils/${name}/index.ts`,
...configOverrides,
domUtils: { root: `fixtures/test-utils/${name}/index.ts`, ...configOverrides },
selectorsUtils: { root: `fixtures/test-utils/${name}/index.ts`, ...configOverrides },
}).domDefinitions;
}
2 changes: 1 addition & 1 deletion test/test-utils/usage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('documentTestUtils throws error for ', () => {
test('having no input files because of a non-matching glob', () => {
expect(() =>
buildTestUtilsProject('simple', {
domUtilsRoot: 'fixtures/does-not-exist/index.ts',
root: 'fixtures/does-not-exist/index.ts',
})
).toThrow(/File '.*fixtures\/does-not-exist\/index.ts' not found/);
});
Expand Down
4 changes: 2 additions & 2 deletions test/test-utils/writer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ test('should write documentation files into the outDir', async () => {

writeTestUtilsDocumentation({
tsconfigPath: pathe.resolve('fixtures/test-utils/simple/tsconfig.json'),
domUtilsRoot: 'fixtures/test-utils/simple/index.ts',
selectorsUtilsRoot: 'fixtures/test-utils/simple/index.ts',
domUtils: { root: 'fixtures/test-utils/simple/index.ts' },
selectorsUtils: { root: 'fixtures/test-utils/simple/index.ts' },
outDir,
});

Expand Down
Loading