bundler/server.test.ts

110 lines
3.2 KiB
TypeScript

import { describe, expect, it, mockfn } from "./deps.testing.ts";
import { processRequest } from "./server.ts";
describe("serveBundles", () => {
it("calls deno bundle if asking for js", async () => {
const runner = mockfn(() => {
return {
output: () => Promise.resolve(new TextEncoder().encode("abc")),
status: () => Promise.resolve({ code: 0, success: true }),
} as any;
});
const { response } = await call("/greatlib@1.0.0/reader/file.js", {
runner,
});
await checkResponse(response, 200, "abc");
expect(runner).toHaveBeenCalledTimes(1);
expect(runner).toHaveBeenCalledWith({
cmd: [
"deno",
"bundle",
"https://git.example.com/libs/greatlib/raw/1.0.0/reader/file.ts",
],
stdout: "piped",
});
});
it("serves raw file if asking for anything other than js", async () => {
const fetcher = mockfn(() => new Response("abc"));
const { response, runner } = await call("/greatlib@1.0.0/reader/file.ts", {
fetcher,
});
await checkResponse(response, 200, "abc");
expect(runner).not.toHaveBeenCalled();
expect(fetcher).toHaveBeenCalledTimes(1);
expect(fetcher).toHaveBeenCalledWith(
"https://git.example.com/libs/greatlib/raw/1.0.0/reader/file.ts",
{ redirect: "follow" },
);
});
it("handles bad method", async () => {
const { response, runner } = await call("/greatlib@1.0.0/reader/file.ts", {
method: "POST",
});
await checkResponse(response, 405);
expect(runner).not.toHaveBeenCalled();
});
it("handles bad path", async () => {
const { response, runner } = await call("/greatlib@1.0.0/reader{}.ts");
await checkResponse(
response,
400,
'console.error("bundler error - Invalid path https://git.example.com/libs/greatlib/raw/1.0.0/reader{}.ts");',
);
expect(runner).not.toHaveBeenCalled();
});
it("handles bundle failure", async () => {
const runner = mockfn(() => {
return {
output: () => Promise.resolve(undefined),
status: () => Promise.resolve({ code: 1, success: false }),
} as any;
});
const { response } = await call("/great_lib@1.0.0-dev1/reader.js", {
runner,
});
await checkResponse(
response,
500,
'console.error("bundler error - Failed to bundle https://git.example.com/libs/great_lib/raw/1.0.0-dev1/reader.ts");',
);
});
});
type CallContext = {
runner: ReturnType<typeof mockfn>;
fetcher: ReturnType<typeof mockfn>;
};
type CallOptions = CallContext & {
method: string;
};
type CallResult = CallContext & {
response: Response;
};
async function call(
path: string,
options: Partial<CallOptions> = {},
): Promise<CallResult> {
const method = options.method ?? "GET";
const runner = options.runner ?? mockfn();
const fetcher = options.fetcher ?? mockfn();
const response = await processRequest(
{ method, url: "http://localhost:8000" + path } as any,
"git.example.com/libs",
runner,
fetcher,
);
return { response, runner, fetcher };
}
async function checkResponse(res: Response, status = 200, body?: string) {
expect(res.status).toEqual(status);
if (body) {
expect(await res.text()).toEqual(body);
} else {
expect(res.body).toBeNull();
}
}