Skip to content

Commit c32ed0f

Browse files
committed
feat(test-utils): automatically serialize json
1 parent 2d44c69 commit c32ed0f

File tree

1 file changed

+28
-24
lines changed

1 file changed

+28
-24
lines changed

src/test-utils.ts

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,35 +6,39 @@ import { fileURLToPath, pathToFileURL } from "node:url";
66
import { onTestFinished } from "vitest";
77

88
export interface Fixture {
9-
root: URL;
10-
resolve: (...segments: string[]) => URL;
11-
readFile: (file: PathLike) => Promise<string>;
12-
cleanup: () => Promise<void>;
9+
root: URL;
10+
resolve: (...segments: string[]) => URL;
11+
readFile: (file: PathLike) => Promise<string>;
12+
cleanup: () => Promise<void>;
1313
}
1414

1515
export async function createFixture(files: Record<string, string>): Promise<Fixture> {
16-
const root = new URL(`bsh-`, `file://${tmpdir()}/`);
17-
const path = await mkdtemp(fileURLToPath(root));
18-
const base = pathToFileURL(path + sep);
16+
const root = new URL(`bsh-`, `file://${tmpdir()}/`);
17+
const path = await mkdtemp(fileURLToPath(root));
18+
const base = pathToFileURL(path + sep);
1919

20-
for (const [name, content] of Object.entries(files)) {
21-
const url = new URL(name, base);
22-
const dir = new URL("./", url);
23-
await mkdir(dir, { recursive: true });
24-
await writeFile(url, content, "utf8");
25-
}
20+
for (const [name, content] of Object.entries(files)) {
21+
const url = new URL(name, base);
22+
const dir = new URL("./", url);
23+
await mkdir(dir, { recursive: true });
24+
if (name.endsWith(".json") && typeof content !== "string") {
25+
await writeFile(url, JSON.stringify(content, null, 2), "utf8");
26+
} else {
27+
await writeFile(url, content, "utf8");
28+
}
29+
}
2630

27-
const cleanup = () => rm(path, { recursive: true, force: true });
28-
onTestFinished(cleanup);
31+
const cleanup = () => rm(path, { recursive: true, force: true });
32+
onTestFinished(cleanup);
2933

30-
const resolve = (...segments: string[]) => new URL(`./${segments.join("/")}`, base);
31-
const readFile = (file: PathLike) =>
32-
fsReadFile(new URL(`./${file}`, base), { encoding: "utf-8" });
34+
const resolve = (...segments: string[]) => new URL(`./${segments.join("/")}`, base);
35+
const readFile = (file: PathLike) =>
36+
fsReadFile(new URL(`./${file}`, base), { encoding: "utf-8" });
3337

34-
return {
35-
root: pathToFileURL(path),
36-
resolve,
37-
readFile,
38-
cleanup,
39-
};
38+
return {
39+
root: pathToFileURL(path),
40+
resolve,
41+
readFile,
42+
cleanup,
43+
};
4044
}

0 commit comments

Comments
 (0)