執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

使用 bun test 匯入、require 和測試 Svelte 元件

使用 Bun 的 外掛 API 為 .svelte 檔案新增自定義載入器,並在 bunfig.toml 中使用 test.preload 選項,在測試執行前載入它。

首先,安裝 @testing-library/svelte、svelte 和 @happy-dom/global-registrator。

terminal
bun add @testing-library/svelte svelte@4 @happy-dom/global-registrator

然後,將以下外掛儲存到你的專案中。

svelte-loader.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({
  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: "dom",
          dev: false,
        });

        return {
          contents: result.js.code,
          loader: "js",
        };
      } catch (err) {
        throw new Error(`編譯 Svelte 元件失敗:${err.message}`);
      }
    });
  },
});

將以下內容新增到 bunfig.toml,以便 Bun 在測試執行前預載入外掛。

bunfig.toml
[test]
# 告訴 Bun 在測試執行前載入此外掛
preload = ["./svelte-loader.ts"]

# This also works, at the top level of bunfig.toml instead of under [test]:
# test.preload = ["./svelte-loader.ts"]

在專案中新增一個範例 .svelte 檔案。

Counter.svelte
<script>
  export let initialCount = 0;
  let count = initialCount;
</script>

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

現在,你可以在測試中 import 或 require *.svelte 檔案。Bun 會將每個 Svelte 元件作為 JavaScript 模組載入。

hello-svelte.test.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");

  // Initial state
  expect(component.$$.ctx[0]).toBe(0); // ctx[0] is count; ctx[1] is initialCount

  // 點選遞增按鈕
  await fireEvent.click(button);

  // 檢查新的狀態
  expect(component.$$.ctx[0]).toBe(1);
});

使用 bun test 來執行測試。

terminal
bun test