microsoft/typespec

Public

mirrored from https://github.com/microsoft/typespecAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/enable-backcompat-top-parameter-another-one

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

packages/asset-emitter/test/host.ts

82lines · modecode

1import { resolvePath } from "@typespec/compiler";
2import { createTestHost, type TypeSpecTestLibrary } from "@typespec/compiler/testing";
3import { fileURLToPath } from "url";
4import { expect, type MockInstance, vi } from "vitest";
5import { createAssetEmitter, TypeEmitter } from "../src/index.js";
6
7export const lib: TypeSpecTestLibrary = {
8 name: "typespec-ts-interface-emitter",
9 packageRoot: resolvePath(fileURLToPath(import.meta.url), "../../../"),
10 files: [
11 {
12 realDir: "",
13 pattern: "package.json",
14 virtualPath: "./node_modules/typespec-ts-interface-emitter",
15 },
16 {
17 realDir: "dist/src",
18 pattern: "*.js",
19 virtualPath: "./node_modules/typespec-ts-interface-emitter/dist/src",
20 },
21 ],
22};
23
24export async function getHostForTypeSpecFile(contents: string, decorators?: Record<string, any>) {
25 const host = await createTestHost();
26 if (decorators) {
27 await host.addJsFile("dec.js", decorators);
28 contents = `import "./dec.js";\n` + contents;
29 }
30 await host.addTypeSpecFile("main.tsp", contents);
31 await host.compile("main.tsp", {
32 outputDir: "tsp-output",
33 });
34 return host;
35}
36
37export async function emitTypeSpec(
38 Emitter: typeof TypeEmitter<any>,
39 code: string,
40 callCounts: Partial<Record<keyof TypeEmitter<any>, number>> = {},
41 validateCallCounts = true,
42) {
43 const host = await getHostForTypeSpecFile(code);
44 const emitter = createAssetEmitter(host.program, Emitter, {
45 emitterOutputDir: "tsp-output",
46 options: {},
47 } as any);
48 const spies = emitterSpies(Emitter);
49 emitter.emitProgram();
50 await emitter.writeOutput();
51 if (validateCallCounts) {
52 assertSpiesCalled(spies, callCounts);
53 }
54 return emitter;
55}
56
57type EmitterSpies = Record<string, MockInstance<any>>;
58function emitterSpies(emitter: typeof TypeEmitter<any, any>) {
59 const spies: EmitterSpies = {};
60 const methods = Object.getOwnPropertyNames(emitter.prototype);
61 for (const key of methods) {
62 if (key === "constructor") continue;
63 if ((emitter.prototype as any)[key].restore) {
64 // assume this whole thing is already spied.
65 return spies;
66 }
67 if (typeof (emitter.prototype as any)[key] !== "function") continue;
68 spies[key] = vi.spyOn(emitter.prototype, key as any);
69 }
70
71 return spies;
72}
73
74function assertSpiesCalled(
75 spies: EmitterSpies,
76 callCounts: Partial<Record<keyof TypeEmitter<any>, number>>,
77) {
78 for (const [key, spy] of Object.entries(spies)) {
79 const expectedCount = (callCounts as any)[key] ?? 1;
80 expect(spy).toHaveBeenCalledTimes(expectedCount);
81 }
82}
83