Plugin API 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, {
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 загружать этот плагин перед запуском тестов.
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>Теперь вы можете 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");
// 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 для запуска тестов.
bash
bun test