Skip to content

L'API de plugins de Bun vous permet d'ajouter des chargeurs personnalisés à votre projet. L'option test.preload dans bunfig.toml vous permet de configurer votre chargeur pour qu'il démarre avant l'exécution de vos tests.

Tout d'abord, installez @testing-library/svelte, svelte et @happy-dom/global-registrator.

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

Ensuite, enregistrez ce plugin dans votre projet.

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(`Échec de la compilation du composant Svelte : ${err.message}`);
      }
    });
  },
});

Ajoutez ceci à bunfig.toml pour indiquer à Bun de précharger le plugin, afin qu'il se charge avant l'exécution de vos tests.

toml
[test]
# Indique à Bun de charger ce plugin avant l'exécution de vos tests
preload = ["./svelte-loader.ts"]

# Ceci fonctionne aussi :
# test.preload = ["./svelte-loader.ts"]

Ajoutez un exemple de fichier .svelte dans votre projet.

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

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

Maintenant, vous pouvez import ou require des fichiers *.svelte dans vos tests, et cela chargera le composant Svelte en tant que module 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");

  // État initial
  expect(component.$$.ctx[0]).toBe(0); // initialCount est la première propriété

  // Cliquer sur le bouton d'incrémentation
  await fireEvent.click(button);

  // Vérifier le nouvel état
  expect(component.$$.ctx[0]).toBe(1);
});

Utilisez bun test pour exécuter vos tests.

bash
bun test

Bun édité par www.bunjs.com.cn