Puoi usare Testing Library con il test runner di Bun.
Come prerequisito per usare Testing Library, dovrai installare Happy Dom. (vedi la guida di Bun su Happy DOM per maggiori informazioni).
bun add -D @happy-dom/global-registratorSuccessivamente, dovresti installare i pacchetti Testing Library che pianifichi di usare. Ad esempio, se stai configurando il testing per React, i tuoi installi potrebbero essere questi. Dovrai anche installare @testing-library/jest-dom per far funzionare i matcher più tardi.
bun add -D @testing-library/react @testing-library/dom @testing-library/jest-domSuccessivamente, dovrai creare uno script di preload per Happy DOM e per Testing Library. Per maggiori dettagli sullo script di setup di Happy DOM, vedi la guida di Bun su Happy DOM.
import { GlobalRegistrator } from "@happy-dom/global-registrator";
GlobalRegistrator.register();Per Testing Library, dovrai estendere la funzione expect di Bun con i matcher di Testing Library. Opzionalmente, per corrispondere meglio al comportamento di test-runner come Jest, potresti voler eseguire il cleanup dopo ogni test.
import { afterEach, expect } from "bun:test";
import { cleanup } from "@testing-library/react";
import * as matchers from "@testing-library/jest-dom/matchers";
expect.extend(matchers);
// Opzionale: pulisce `render` dopo ogni test
afterEach(() => {
cleanup();
});Successivamente, aggiungi questi script di preload al tuo bunfig.toml (puoi anche avere tutto in un unico script preload.ts se preferisci).
[test]
preload = ["./happydom.ts", "./testing-library.ts"]Se stai usando TypeScript, dovrai anche usare il declaration merging per far apparire i nuovi tipi di matcher nel tuo editor. Per fare questo, crea un file di dichiarazione dei tipi che estende Matchers in questo modo.
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 {}
}Ora dovresti essere in grado di usare Testing Library nei tuoi test.
import { test, expect } from "bun:test";
import { screen, render } from "@testing-library/react";
import { MyComponent } from "./myComponent";
test("Può usare Testing Library", () => {
render(MyComponent);
const myComponent = screen.getByTestId("my-component");
expect(myComponent).toBeInTheDocument();
});Fai riferimento alla documentazione di Testing Library, al repo di Happy DOM e a Docs > Test runner > DOM per la documentazione completa sulla scrittura di test del browser con Bun.