Skip to content

Bun 的 插件 API 允許你向項目添加自定義加載器。bunfig.toml 中的 test.preload 選項允許你配置加載器在測試運行之前啟動。

首先,安裝 @testing-library/sveltesvelte@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, {
          filetitle: 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 在測試運行之前預加載插件。

toml
[test]
# 告訴 Bun 在測試運行之前預加載此插件
preload = ["./svelte-loader.ts"]

# 這也有效:
# test.preload = ["./svelte-loader.ts"]

在你的項目中添加一個示例 .svelte 文件。

html
<script>
  export let initialCount = 0;
  let count = initialCount;
</script>

<button on:click={() => (count += 1)}>+1</button>

現在你可以在測試中 importrequire *.svelte 文件,它將把 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

Bun學習網由www.bunjs.com.cn整理維護