Skip to content
File

Blob: types/test/transforms/class-to-interface.spec.ts

typescript60 lines
1// Copyright (c) 2022-2023 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5import assert from "assert";
6import { test } from "node:test";
7import path from "path";
8import ts from "typescript";
9import { printer } from "../../src/print";
10import { createMemoryProgram } from "../../src/program";
11import { createClassToInterfaceTransformer } from "../../src/transforms/class-to-interface";
12 
13test("createClassToInterfaceTransformer: transforms class to interface", () => {
14 const source = `
15 class MyClass<T = void, U = void> {
16 constructor(str: string): MyClass;
17 prop: T;
18 method(): U {}
19 get accessor(): number { return 42; }
20 static staticMethod(str?: string): void {}
21 private privateMethod() {}
22 }
23 `;
24 
25 const expectedOutput = `
26 declare var MyClass: {
27 prototype: MyClass;
28 new <T = void, U = void>(str: string): MyClass<T, U>;
29 staticMethod(str?: string): void;
30 };
31 interface MyClass<T = void, U = void> {
32 prop: T;
33 method(): U;
34 accessor: number;
35 }
36 `;
37 
38 const sourcePath = path.resolve(__dirname, "source.ts");
39 const sources = new Map([[sourcePath, source]]);
40 const program = createMemoryProgram(sources);
41 const sourceFile = program.getSourceFile(sourcePath);
42 assert(sourceFile !== undefined);
43 
44 const result = ts.transform(sourceFile, [
45 createClassToInterfaceTransformer(["MyClass"]),
46 ]);
47 assert.strictEqual(result.transformed.length, 1);
48 
49 const output = printer.printFile(result.transformed[0]);
50 assert.strictEqual(
51 normalizeWhitespace(output.trim()),
52 normalizeWhitespace(expectedOutput.trim()),
53 "The transformed output did not match the expected output"
54 );
55});
56 
57function normalizeWhitespace(str: string) {
58 return str.replace(/\s+/g, " ").trim();
59}