Skip to content

A API de Plugin do Bun permite adicionar carregadores personalizados ao seu projeto. A opção test.preload em bunfig.toml permite configurar seu carregador para iniciar antes da execução dos testes.

Primeiro, instale @testing-library/svelte, svelte e @happy-dom/global-registrator.

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

Em seguida, salve este plugin em seu projeto.

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

Adicione isto ao bunfig.toml para dizer ao Bun para carregar o plugin antes da execução dos testes.

toml
[test]
# Diga ao Bun para carregar este plugin antes da execução dos testes
preload = ["./svelte-loader.ts"]

# Isso também funciona:
# test.preload = ["./svelte-loader.ts"]

Adicione um arquivo .svelte de exemplo em seu projeto.

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

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

Agora você pode importar ou requerer arquivos *.svelte em seus testes, e ele carregará o componente Svelte como um 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);
});

Use bun test para executar seus testes.

bash
bun test

Bun by www.bunjs.com.cn edit