Skip to content

Il test runner di Bun supporta il testing di snapshot in stile Jest tramite .toMatchSnapshot().

ts
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.)

sh
bun test test/snap
txt
test/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.

txt
test
├── __snapshots__
│   └── snap.test.ts.snap
└── snap.test.ts

Il 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.

js
// 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à.

sh
bun test
txt
bun 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.

sh
bun test --update-snapshots
txt
bun 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.

Bun a cura di www.bunjs.com.cn