Skip to content

Commit

Permalink
test: reuse similar logic
Browse files Browse the repository at this point in the history
  • Loading branch information
metonym committed Apr 8, 2024
1 parent cc67f77 commit 55c8ae6
Showing 1 changed file with 21 additions and 20 deletions.
41 changes: 21 additions & 20 deletions tests/fixtures.test.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,41 @@
import fg from "fast-glob";
import fs from "node:fs"
import fsp from "node:fs/promises";
import path from "node:path";
import ComponentParser from "../src/ComponentParser";
import Writer from "../src/writer/Writer";
import { writeTsDefinition } from "../src/writer/writer-ts-definitions";

const folder = path.join(process.cwd(), "tests", "fixtures");

const svelteFiles = fg.sync(["**/*.svelte"], { cwd: folder });
const fixtures = await Promise.all(
svelteFiles.map(async (file) => {
return {
path: file,
source: await fsp.readFile(path.join(folder, file), "utf-8"),
};
})
);

const createMetadata = (filePath: string) => {
const { dir } = path.parse(filePath);
const fixtures = svelteFiles.map((file) => {
return {
path: file,
source: fs.readFileSync(path.join(folder, file), "utf-8"),
};
});

const parser = new ComponentParser();
const writer = new Writer({ parser: "typescript", printWidth: 120 });

const getMetadata = (fixture: (typeof fixtures)[0]) => {
const { dir } = path.parse(fixture.path);
const moduleName = dir
.split("-")
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
.join("");
const metadata = { moduleName, filePath: fixture.path };
const parsed_component = parser.parseSvelteComponent(fixture.source, {
filePath: fixture.path,
moduleName,
});

return { dir, moduleName, filePath };
return { dir, metadata, parsed_component };
};

const parser = new ComponentParser();
const writer = new Writer({ parser: "typescript", printWidth: 120 });

describe("fixtures (JSON)", async () => {
test.concurrent.each(fixtures)("$path", async (fixture) => {
const { dir, ...metadata } = createMetadata(fixture.path);
const parsed_component = parser.parseSvelteComponent(fixture.source, metadata);
const { dir, parsed_component } = getMetadata(fixture);
const api_json = JSON.stringify(parsed_component, null, 2);

// Snapshot the output; if the test fails, output has changed.
Expand All @@ -46,8 +48,7 @@ describe("fixtures (JSON)", async () => {

describe("fixtures (TypeScript)", async () => {
test.concurrent.each(fixtures)("$path", async (fixture) => {
const { dir, ...metadata } = createMetadata(fixture.path);
const parsed_component = parser.parseSvelteComponent(fixture.source, metadata);
const { dir, metadata, parsed_component } = getMetadata(fixture);
const api_ts = writer.format(writeTsDefinition({ ...metadata, ...parsed_component }));

// Snapshot the output; if the test fails, output has changed.
Expand Down

0 comments on commit 55c8ae6

Please sign in to comment.