Bun の プラグイン API を使用してプロジェクトにカスタムローダーを追加できます。bunfig.toml の test.preload オプションを使用すると、テスト実行前にローダーを開始するように構成できます。
まず、@testing-library/svelte、svelte、および @happy-dom/global-registrator をインストールします。
bash
bun add @testing-library/svelte svelte@4 @happy-dom/global-registrator次に、このプラグインをプロジェクトに保存します。
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, {
filename: path,
generate: "client",
dev: false,
});
return {
contents: result.js.code,
loader: "js",
};
} catch (err) {
throw new Error(`Svelte コンポーネントのコンパイルに失敗しました:${err.message}`);
}
});
},
});テスト実行前にプラグインを読み込むように Bun に指示するには、これを bunfig.toml に追加します。
toml
[test]
# テスト実行前にこのプラグインを読み込むように Bun に指示
preload = ["./svelte-loader.ts"]
# これでも動作します:
# test.preload = ["./svelte-loader.ts"]プロジェクトにサンプルの .svelte ファイルを追加します。
html
<script>
export let initialCount = 0;
let count = initialCount;
</script>
<button onclick={() => (count += 1)}>+1</button>これで、テスト内で *.svelte ファイルを import または require でき、Svelte コンポーネントを JavaScript モジュールとして読み込みます。
ts
import { test, expect } from "bun:test";
import { render, fireEvent } from "@testing-library/svelte";
import Counter from "./Counter.svelte";
test("クリック時にカウンターが増加", async () => {
const { getByText, component } = render(Counter);
const button = getByText("+1");
// 初期状態
expect(component.$$.ctx[0]).toBe(0); // initialCount が最初のプロパティです
// 増分ボタンをクリック
await fireEvent.click(button);
// 新しい状態を確認
expect(component.$$.ctx[0]).toBe(1);
});bun test を使用してテストを実行します。
bash
bun test