Bun 的 外掛程式 API 讓您可以將自訂載入器新增至您的專案。bunfig.toml
中的 test.preload
選項讓您可以設定載入器在測試執行前啟動。
首先,安裝 @testing-library/svelte
、svelte
和 @happy-dom/global-registrator
。
bun add @testing-library/svelte svelte@4 @happy-dom/global-registrator
然後,將此外掛程式儲存到您的專案中。
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({
name: "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(`Failed to compile Svelte component: ${err.message}`);
}
});
},
});
將此新增至 bunfig.toml
以告知 Bun 預先載入此外掛程式,使其在您的測試執行前載入。
[test]
# Tell Bun to load this plugin before your tests run
preload = ["./svelte-loader.js"]
# This also works:
# test.preload = ["./svelte-loader.js"]
在您的專案中新增範例 .svelte
檔案。
<script>
export let initialCount = 0;
let count = initialCount;
</script>
<button on:click={() => (count += 1)}>+1</button>
現在您可以在測試中 import
或 require
*.svelte
檔案,它會將 Svelte 元件載入為 JavaScript 模組。
import { test, expect } from "bun:test";
import { render, fireEvent } from "@testing-library/svelte";
import Counter from "./Counter.svelte";
test("Counter increments when clicked", async () => {
const { getByText, component } = render(Counter);
const button = getByText("+1");
// Initial state
expect(component.$$.ctx[0]).toBe(0); // initialCount is the first prop
// Click the increment button
await fireEvent.click(button);
// Check the new state
expect(component.$$.ctx[0]).toBe(1);
});
使用 bun test
執行您的測試。
bun test