您可以搭配 Bun 的測試執行器使用 Testing Library。
使用 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();
})
請參閱 Testing Library 文件、Happy DOM repo 和 文件 > 測試執行器 > DOM,以取得使用 Bun 撰寫瀏覽器測試的完整文件。