📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHPUnit Testing Snapshot Testing

Snapshot Testing

4 min read
Compare JSON, HTML, and other outputs to stored snapshots with spatie/phpunit-snapshot-assertions.

Snapshot Testing

composer require --dev spatie/phpunit-snapshot-assertions

use SpatieSnapshotsMatchesSnapshots;

class ReportTest extends TestCase {
    use MatchesSnapshots;

    public function testReportFormat(): void {
        $report = (new ReportGenerator)->generate([
            ["name" => "Alice", "sales" => 1500],
            ["name" => "Bob",   "sales" => 800],
        ]);

        // First run: creates snapshot file
        // Subsequent runs: compares to snapshot
        $this->assertMatchesSnapshot($report);
    }

    public function testHtmlOutput(): void {
        $html = (new View)->render("report", $data);
        $this->assertMatchesHtmlSnapshot($html);
    }

    public function testJsonApi(): void {
        $json = (new ApiClient)->get("/users");
        $this->assertMatchesJsonSnapshot($json);
    }
}