Skip to content

تسمح لك واجهة برمجة تطبيقات الإضافات في Bun بإضافة محملات مخصصة إلى مشروعك. خيار test.preload في bunfig.toml يسمح لك بتكوين المحمل الخاص بك للبدء قبل تشغيل اختباراتك.

أولاً، قم بتثبيت @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, {
          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>

الآن يمكنك import أو require ملفات *.svelte في اختباراتك، وسيتم تحميل مكون Svelte كوحدة JavaScript.

ts
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");

  // الحالة الأولية
  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 تحرير