> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 bun test 导入、require 和测试 Svelte 组件

使用 Bun 的[插件 API](/runtime/plugins) 为 `.svelte` 文件添加自定义加载器，并在 `bunfig.toml` 中使用 `test.preload` 选项，使其在测试运行前加载。

首先，安装 `@testing-library/svelte`、`svelte` 和 `@happy-dom/global-registrator`。

```bash terminal icon="terminal" theme={null}
bun add @testing-library/svelte svelte@4 @happy-dom/global-registrator
```

然后，将此插件保存到项目中。

```ts svelte-loader.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
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({
  name: "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, {
          filetitle: path,
          generate: "client",
          dev: false,
        });

        return {
          contents: result.js.code,
          loader: "js",
        };
      } catch (err) {
        throw new Error(`编译 Svelte 组件失败：${err.message}`);
      }
    });
  },
});
```

***

将此配置添加到 `bunfig.toml`，使 Bun 在测试运行前预加载该插件。

```toml bunfig.toml icon="settings" theme={null}
[test]
# 告诉 Bun 在测试运行前加载此插件
preload = ["./svelte-loader.ts"]

# 这样也可以：
# test.preload = ["./svelte-loader.ts"]
```

***

在项目中添加一个示例 `.svelte` 文件。

```html Counter.svelte icon="file-code" theme={null}
<script>
  export let initialCount = 0;
  let count = initialCount;
</script>

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

***

现在你可以在测试中 `import` 或 `require` `*.svelte` 文件。Bun 会将每个 Svelte 组件作为 JavaScript 模块加载。

```ts hello-svelte.test.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
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 terminal icon="terminal" theme={null}
bun test
```
