Skip to content

Bun 의 플러그인 API 를 사용하면 프로젝트에 커스텀 로더를 추가할 수 있습니다. bunfig.tomltest.preload 옵션을 사용하면 테스트 실행 전에 로더가 시작되도록 구성할 수 있습니다.

먼저 @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(`Svelte 컴포넌트 컴파일 실패: ${err.message}`);
      }
    });
  },
});

Bun 이 플러그인을 미리 로드하도록 하려면 bunfig.toml 에 다음을 추가하세요.

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>

이제 테스트에서 *.svelte 파일을 import 또는 require 할 수 있으며 Svelte 컴포넌트가 JavaScript 모듈로 로드됩니다.

ts
import { test, expect } from "bun:test";
import { render, fireEvent } from "@testing-library/svelte";
import Counter from "./Counter.svelte";

test("클릭 시 카운터 증가", 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 by www.bunjs.com.cn 편집