Skip to content

La API de Plugins de Bun te permite agregar cargadores personalizados a tu proyecto. La opción test.preload en bunfig.toml te permite configurar tu cargador para que se inicie antes de que se ejecuten tus pruebas.

Primero, instala @testing-library/svelte, svelte, y @happy-dom/global-registrator.

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

Luego, guarda este plugin en tu proyecto.

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}`);
      }
    });
  },
});

Agrega esto a bunfig.toml para indicarle a Bun que precargue el plugin, para que se cargue antes de que se ejecuten tus pruebas.

toml
[test]
# Indicar a Bun que cargue este plugin antes de que se ejecuten tus pruebas
preload = ["./svelte-loader.ts"]

# Esto también funciona:
# test.preload = ["./svelte-loader.ts"]

Agrega un archivo .svelte de ejemplo en tu proyecto.

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

<button onclick={() => (count += 1)}>+1</button>

Ahora puedes import o require archivos *.svelte en tus pruebas, y cargará el componente Svelte como un módulo 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);
});

Usa bun test para ejecutar tus pruebas.

bash
bun test

Bun por www.bunjs.com.cn editar