@competent-devs/test-forge
Version:
Package for UI unit test generation based on storybook context
81 lines (68 loc) • 2.46 kB
text/typescript
import * as path from "path";
import { logToFile } from "./logger.js";
import { createVitest } from "vitest/node";
export async function runVitest(
testFilePath: string,
): Promise<{ hasErrors: boolean; errors?: string }> {
logToFile(`Running tests for ${testFilePath}`);
const vitest = await createVitest("test", {
watch: false,
reporters: "default",
// workspace: path.join(process.cwd(), "./vitest.workspace.ts"),
// config: path.join(process.cwd(), "./vitest.config.ts"),
});
vitest.config.setupFiles = [".storybook/vitest.setup.ts"];
vitest.config.include = [...vitest.config.include, "**/*.stories.test.tsx"];
await vitest.start([testFilePath]);
const finalResult = { hasErrors: false, errors: "" };
if (vitest) {
await vitest.close();
// Retrieve test results
const testFiles = vitest.state.getFiles();
testFiles.forEach((file) => {
const testFile = vitest.state.getReportedEntity(file);
if (testFile) {
// @ts-ignore
testFile?.task?.tasks.forEach((task) => {
if (task.type === "test") {
const result = task.result;
if (result) {
if (result.errors) {
const errorMessages = result.errors.map((error: any) => {
return `\nStory name - ${task.name}, error - ${error?.message}`;
});
finalResult.hasErrors = true;
finalResult.errors += `\n\n${errorMessages}`;
}
}
}
});
}
});
}
logToFile(
`Test results: has errors - ${finalResult.hasErrors}, errors - ${finalResult.errors}`,
);
return finalResult;
}
// import { exec } from "child_process";
// import path from "path";
// import { logToFile } from "./logger.js";
// const ROOT_DIR = path.resolve("./");
// const logFilePath = path.join(ROOT_DIR, "app.log");
// export async function runVitest(
// testFilePath: string,
// ): Promise<{ hasErrors: boolean; errors?: string }> {
// console.log(`Running tests for ${testFilePath}...`);
// logToFile(`Running tests for ${testFilePath}...`, logFilePath);
// return new Promise((resolve) => {
// exec(`npx vitest run ${testFilePath}`, (error, stdout, stderr) => {
// console.log(stdout);
// if (error) {
// resolve({ hasErrors: true, errors: stderr });
// } else {
// resolve({ hasErrors: false });
// }
// });
// });
// }