test(cli): add tests for serve()

This commit is contained in:
Ayo Ayco 2024-12-07 19:25:29 +01:00
parent 6c14bbf2b5
commit 47fa380ef0
2 changed files with 84 additions and 22 deletions

View file

@ -3,35 +3,44 @@
import { consola } from "consola";
import { colorize } from "consola/utils";
import { defineCommand } from "citty";
import { execSync as exec } from "node:child_process";
import { execSync } from "node:child_process";
import { createRequire } from "node:module";
async function printInfo() {
try {
const _require = createRequire(import.meta.url);
const mcflyPkg = await _require("@mcflyjs/core/package.json");
const mcflyPkgVersion = `McFly ${colorize("bold", mcflyPkg.version)}`;
const nitroPkg = await _require("nitropack/package.json");
const nitroPkgVersion = `Nitro ${nitroPkg.version}`;
consola.log(
`${colorize("blue", mcflyPkgVersion)} ${colorize("dim", nitroPkgVersion)}`
);
} catch (e) {
consola.error(e);
}
}
function serve() {
try {
execSync(`npx nitropack dev`, { stdio: "inherit" });
} catch (e) {
consola.error(e);
}
}
export default defineCommand({
meta: {
name: "prepare",
description: "Runs the dev server.",
},
async run() {
try {
const _require = createRequire(import.meta.url);
const mcflyPkg = await _require("@mcflyjs/core/package.json");
const mcflyPkgVersion = `McFly ${colorize("bold", mcflyPkg.version)}`;
const nitroPkg = await _require("nitropack/package.json");
const nitroPkgVersion = `Nitro ${nitroPkg.version}`;
consola.log(
`${colorize("blue", mcflyPkgVersion)} ${colorize(
"dim",
nitroPkgVersion
)}`
);
} catch (e) {
consola.error(e);
}
try {
exec(`npx nitropack dev`, { stdio: "inherit" });
} catch (e) {
consola.error(e);
}
await printInfo();
serve();
},
});
export const exportedForTest = {
serve,
printInfo,
};

View file

@ -0,0 +1,53 @@
import { describe, expect, test, vi } from "vitest";
import { exportedForTest } from "../commands/serve.mjs";
import consola from "consola";
describe("FUNCTION: serve()", () => {
const testFn = exportedForTest.serve;
const mocks = vi.hoisted(() => {
return {
execSync: vi.fn(),
};
});
vi.mock("node:child_process", () => {
return {
execSync: mocks.execSync,
};
});
test("execute nitropack serve", async () => {
const command = `npx nitropack dev`;
const param = { stdio: "inherit" };
testFn();
expect(mocks.execSync).toHaveBeenCalledWith(command, param);
});
test("catch error", () => {
const spy = vi.spyOn(consola, "error");
mocks.execSync.mockImplementationOnce(() => {
throw new Error("hey");
});
testFn();
expect(spy).toHaveBeenCalledWith(new Error("hey"));
});
});
/**
* TODO: test printInfo
*/
// describe("FUNCTION: printInfo()", () => {
// const testFn = exportedForTest.printInfo;
// test("log mcfly and nitro versions", () => {
// const spy = vi.spyOn(consola, "log");
// testFn();
// expect(spy).toHaveBeenCalled();
// });
// });