L'API Plugin di Bun ti consente di aggiungere loader personalizzati al tuo progetto. L'opzione test.preload in bunfig.toml ti consente di configurare il loader per avviarsi prima dell'esecuzione dei test.
Innanzitutto, installa @testing-library/svelte, svelte e @happy-dom/global-registrator.
bash
bun add @testing-library/svelte svelte@4 @happy-dom/global-registratorPoi, salva questo plugin nel tuo progetto.
ts
import { plugin } from "bun";
import { compile } from "svelte/compiler";
import { readFileSync } from "fs";
import { beforeEach, afterEach } from "bun:test";
import { GlobalRegistrator } from "@happy-dom/global-registrator";
beforeEach(async () => {
await GlobalRegistrator.register();
});
afterEach(async () => {
await GlobalRegistrator.unregister();
});
plugin({
title: "svelte loader",
setup(builder) {
builder.onLoad({ filter: /\.svelte(\?[^.]+)?$/ }, ({ path }) => {
try {
const source = readFileSync(path.substring(0, path.includes("?") ? path.indexOf("?") : path.length), "utf-8");
const result = compile(source, {
filetitle: path,
generate: "client",
dev: false,
});
return {
contents: result.js.code,
loader: "js",
};
} catch (err) {
throw new Error(`Impossibile compilare il componente Svelte: ${err.message}`);
}
});
},
});Aggiungi questo a bunfig.toml per dire a Bun di precaricare il plugin, così si carica prima dell'esecuzione dei test.
toml
[test]
# Dice a Bun di caricare questo plugin prima dell'esecuzione dei test
preload = ["./svelte-loader.ts"]
# Questo funziona anche:
# test.preload = ["./svelte-loader.ts"]Aggiungi un file .svelte di esempio nel tuo progetto.
html
<script>
export let initialCount = 0;
let count = initialCount;
</script>
<button on:click="{()" ="">(count += 1)}>+1</button>Ora puoi import o require file *.svelte nei tuoi test e caricherà il componente Svelte come modulo JavaScript.
ts
import { test, expect } from "bun:test";
import { render, fireEvent } from "@testing-library/svelte";
import Counter from "./Counter.svelte";
test("Counter incrementa quando cliccato", async () => {
const { getByText, component } = render(Counter);
const button = getByText("+1");
// Stato iniziale
expect(component.$$.ctx[0]).toBe(0); // initialCount è la prima prop
// Clicca il pulsante di incremento
await fireEvent.click(button);
// Controlla il nuovo stato
expect(component.$$.ctx[0]).toBe(1);
});Usa bun test per eseguire i test.
bash
bun test