All files / apps/web/src/pages/api coverage.ts

35% Statements 7/20
20% Branches 2/10
33.33% Functions 1/3
36.84% Lines 7/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49              6x                                           6x       6x     6x         6x 6x 6x          
import { createFileRoute } from "@tanstack/react-router";
import * as fs from "node:fs/promises";
import path from "node:path";
import { stopCoverage, takeCoverage } from "node:v8";
 
import { env } from "~web/utils/env";
 
const getCoverage = async () => {
	const serverCoveragePath = env.NODE_V8_COVERAGE;
	if (!serverCoveragePath) {
		throw new Error(
			"Expected to have NODE_V8_COVERAGE when coverage is called",
		);
	}
	const serverFiles = await fs.readdir(serverCoveragePath).catch(() => []);
	if (serverFiles.length === 0) {
		throw new Error(
			"Expected to have at least one coverage file when coverage is called",
		);
	}
	for (const serverFile of serverFiles) {
		if (!serverFile.endsWith(".json")) {
			continue;
		}
		return fs.readFile(path.join(serverCoveragePath, serverFile), "utf8");
	}
};
 
// Flushes V8 coverage to `NODE_V8_COVERAGE` directory, it is processed by the test runner
export const Route = createFileRoute("/api/coverage")({
	server: {
		handlers: {
			POST: async () => {
				Iif (!env.PLAYWRIGHT) {
					return new Response(null, { status: 404 });
				}
				Iif (!env.NODE_V8_COVERAGE) {
					throw new Error(
						"Expected to have NODE_V8_COVERAGE when coverage is called",
					);
				}
				takeCoverage();
				stopCoverage();
				return new Response(await getCoverage());
			},
		},
	},
});