您可以使用 Testing Library 和 Bun 的測試執行器。
在使用 Testing Library 之前,您需要安裝 Happy Dom。 (有關更多資訊,請參閱 Bun 的 Happy DOM 指南)。
bun add -D @happy-dom/global-registrator
接下來,您應該安裝您計劃使用的 Testing Library 包。例如,如果您正在為 React 設定測試,您的安裝可能如下所示。您還需要安裝 @testing-library/jest-dom 以便稍後使匹配器正常工作。
bun add -D @testing-library/react @testing-library/dom @testing-library/jest-dom
接下來,您需要為 Happy DOM 和 Testing Library 建立一個預載入指令碼。有關 Happy DOM 設定指令碼的更多詳細資訊,請參閱 Bun 的 Happy DOM 指南。
import { GlobalRegistrator } from '@happy-dom/global-registrator';
GlobalRegistrator.register();
對於 Testing Library,您將希望使用 Testing Library 的匹配器擴充套件 Bun 的 expect 函式。 可選地,為了更好地匹配 Jest 等測試執行器的行為,您可能希望在每次測試後執行清理。
import { afterEach, expect } from 'bun:test';
import { cleanup } from '@testing-library/react';
import * as matchers from '@testing-library/jest-dom/matchers';
expect.extend(matchers);
// Optional: cleans up `render` after each test
afterEach(() => {
cleanup();
});
接下來,將這些預載入指令碼新增到您的 bunfig.toml 中(如果您願意,也可以將所有內容放在一個 preload.ts 指令碼中)。
[test]
preload = ["./happydom.ts", "./testing-library.ts"]
如果您使用 TypeScript,您還需要利用宣告合併,以便新的匹配器型別能在您的編輯器中顯示。要做到這一點,請建立一個型別宣告檔案,該檔案像這樣擴充套件 Matchers。
import { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers';
import { Matchers, AsymmetricMatchers } from 'bun:test';
declare module 'bun:test' {
interface Matchers<T>
extends TestingLibraryMatchers<typeof expect.stringContaining, T> {}
interface AsymmetricMatchers extends TestingLibraryMatchers {}
}
您現在應該可以在您的測試中使用 Testing Library 了
import { test, expect } from "bun:test";
import { screen, render } from "@testing-library/react";
import { MyComponent } from "./myComponent";
test("Can use Testing Library", () => {
render(MyComponent);
const myComponent = screen.getByTestId("my-component");
expect(myComponent).toBeInTheDocument();
});
有關使用 Bun 編寫瀏覽器測試的完整文件,請參閱 Testing Library 文件、Happy DOM 倉庫 和 文件 > 測試執行器 > DOM。