babel-tailwind/src/index.test.ts
2024-03-29 20:30:18 -04:00

74 lines
2.0 KiB
TypeScript

import { promises as fs } from "node:fs";
import { resolve } from "node:path";
import { build } from "esbuild";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
type TailwindPluginOptions,
babelPlugin,
getClassName,
getTailwindPlugins,
} from "./index";
const folder = resolve(import.meta.dirname, "temp");
describe("babel-tailwind", () => {
beforeEach(async () => {
await fs.mkdir(folder, { recursive: true });
});
afterEach(async () => {
await fs.rm(folder, { recursive: true, force: true });
});
async function write(path: string, content: string) {
const resolved = resolve(folder, path);
await fs.writeFile(resolved, content);
return resolved;
}
async function compile(options: TailwindPluginOptions, javascript: string) {
const tailwind = getTailwindPlugins(options);
const result = await build({
bundle: true,
write: false,
external: ["react/jsx-runtime"],
outdir: "dist",
format: "esm",
entryPoints: [await write("index.tsx", javascript)],
plugins: [babelPlugin({ getPlugins: () => [tailwind.babel] }), tailwind.esbuild],
});
const { errors, warnings, outputFiles } = result;
expect(errors).toHaveLength(0);
expect(warnings).toHaveLength(0);
return outputFiles;
}
it("renders", async () => {
const outputFiles = await compile(
{
tailwindConfig: {},
clsx: "emotion",
},
/* tsx */ `
export function Hello() {
return (
<div css="text-center">
Hello, world!
</div>
);
}
`
);
expect(outputFiles).toHaveLength(2);
const js = outputFiles.find(file => file.path.endsWith(".js"))!;
const css = outputFiles.find(file => file.path.endsWith(".css"))!;
const clsName = getClassName("text-center");
expect(js.text).toContain(`className: "${clsName}"`);
expect(css.text).toMatch(`.${clsName} {\n text-align: center;\n}`);
});
});