spatie/pest-plugin-snapshots
Add snapshot testing to Pest. Assert strings, JSON, and more against stored snapshots using helper functions or Pest expectations like toMatchSnapshot(). Built on Spatieβs phpunit-snapshot-assertions for easy, reliable regression testing.
Install the package as a dev dependency β no extra configuration needed:
composer require spatie/pest-plugin-snapshots --dev
After installation, the first snapshot test run will automatically create the tests/Snapshots/ directory and generate snapshot files. Use one of the three core patterns to assert output:
it('outputs correct string', function () {
$result = (new Order(1))->toString();
expect($result)->toMatchSnapshot();
});
it('returns expected JSON', function () {
$response = $this->getJson('/api/orders/1')->json();
assertMatchesJsonSnapshot($response);
});
Start by reading the README and the underlying phpunit-snapshot-assertions docs β this plugin is a thin, API-compatible wrapper.
Use expectation syntax for fluency or function calls for control:
| Scenario | Pest Expectation | Functional |
|---|---|---|
| Plain text / HTML | expect($html)->toMatchSnapshot() |
assertMatchesSnapshot($html) |
| JSON / arrays | expect($data)->toMatchJsonSnapshot() |
assertMatchesJsonSnapshot($data) |
| Images | expect($imagePath)->toMatchImageSnapshot() |
assertMatchesImageSnapshot($imagePath) |
Group by feature/context using custom IDs to avoid fragile filenames:
it('creates an order', function () {
$order = Order::create(['amount' => 99.99]);
expect($order->toArray())->toMatchSnapshot('orders/create');
});
it('updates an order', function () {
$order->update(['amount' => 149.99]);
expect($order->toArray())->toMatchSnapshot('orders/update');
});
β Files: tests/Snapshots/Feature/Orders/Order_creates_an_order.orders_create.snapshot
pest --update-snapshotspest --no-interaction (no prompts, fails on mismatch)pest --clean-snapshots (v2.3.0+)pest --only-failed --difftrim(), preg_replace('/\s+/', ' ', $str)) β especially important when generating HTML/Markdown.['secret' => 'REDACTED']) or use custom ID generators to redact.tests/Snapshots/, but can be customized via SNAPSHOT_PATH in phpunit.xml.spatie/phpunit-snapshot-assertions ^5.3.1 matches plugin requirements (v2.3.0+).tests/Snapshots/ is writable.SnapshotIdAware trait in your test cases or Pest config.tests/Pest.php:
function snapshot_json($data, string $id = ''): void {
assertMatchesJsonSnapshot($data, $id);
}
phpunit.xml:
<php>
<server name="SNAPSHOT_PATH" value="tests/_snapshots"/>
</php>
tests/Feature/... to match project structure.How can I help you explore Laravel packages today?