Il test runner di Bun supporta il testing di snapshot in stile Jest tramite .toMatchSnapshot().
import { test, expect } from "bun:test";
test("snapshot", () => {
expect({ foo: "bar" }).toMatchSnapshot();
});La prima volta che questo test viene eseguito, Bun valuterà il valore passato a expect() e lo scriverà su disco in una directory chiamata __snapshots__ che si trova accanto al file di test. (Nota la riga snapshots: +1 added nell'output.)
bun test test/snaptest/snap.test.ts:
✓ snapshot [1.48ms]
1 pass
0 fail
snapshots: +1 added
1 expect() calls
Ran 1 tests across 1 files. [82.00ms]La directory __snapshots__ contiene un file .snap per ogni file di test nella directory.
test
├── __snapshots__
│ └── snap.test.ts.snap
└── snap.test.tsIl file snap.test.ts.snap è un file JavaScript che esporta una versione serializzata del valore passato a expect(). L'oggetto {foo: "bar"} è stato serializzato in JSON.
// Bun Snapshot v1, https://bun.com/docs/test/snapshots
exports[`snapshot 1`] = `
{
"foo": "bar",
}
`;Successivamente, quando questo file di test viene eseguito di nuovo, Bun leggerà il file di snapshot e lo confronterà con il valore passato a expect(). Se i valori sono diversi, il test fallirà.
bun testbun test v1.3.3 (9c68abdb)
test/snap.test.ts:
✓ snapshot [1.05ms]
1 pass
0 fail
1 snapshots, 1 expect() calls
Ran 1 tests across 1 files. [101.00ms]Per aggiornare gli snapshot, usa il flag --update-snapshots.
bun test --update-snapshotsbun test v1.3.3 (9c68abdb)
test/snap.test.ts:
✓ snapshot [0.86ms]
1 pass
0 fail
snapshots: +1 added # lo snapshot è stato rigenerato
1 expect() calls
Ran 1 tests across 1 files. [102.00ms]Vedi Docs > Test Runner > Snapshots per la documentazione completa sugli snapshot con il test runner di Bun.