Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

phpunit-snapshot-assertions

> 测试质量
Open source

A way to test without writing actual test cases

697 stars0 likes1 views
WebsiteGitHub

About

A way to test without writing actual test cases

Snapshot testing is a way to test without writing actual test cases.

You can learn more in this free video from our Testing Laravel course. Don't worry you can use this package in non-Laravel projects too.

php
use Spatie\Snapshots\MatchesSnapshots;

class OrderTest
{
    use MatchesSnapshots;

    public function test_it_casts_to_json()
    {
        $order = new Order(1);

        $this->assertMatchesJsonSnapshot($order->toJson());
    }
}

On the first run, the test runner will create a new snapshot.

> ./vendor/bin/phpunit

There was 1 incomplete test:

1) OrderTest::test_it_casts_to_json
Snapshot created for OrderTest__test_it_casts_to_json__1

OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 0, Incomplete: 1.

On subsequent runs, the test will pass as long as the snapshot doesn't change.

> ./vendor/bin/phpunit

OK (1 test, 1 assertion)

If there's a regression, the test will fail!

php
$orderId = new Order(2); // Regression! Was `1`
> ./vendor/bin/phpunit

1) OrderTest::test_it_casts_to_json
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
Failed asserting that '{"id":2}' matches JSON string "{
    "id": 1
}

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

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

Usage

To make snapshot assertions, use the Spatie\Snapshots\MatchesSnapshots trait in your test case class. This adds a set of assertion methods to the class:

  • assertMatchesSnapshot($actual, $driver, $id)
  • assertMatchesFileHashSnapshot($filePath, $id)
  • assertMatchesFileSnapshot($file, $id)
  • assertMatchesHtmlSnapshot($actual, $id)
  • assertMatchesJsonSnapshot($actual, $id)
  • assertMatchesObjectSnapshot($actual, $id)
  • assertMatchesTextSnapshot($actual, $id)
  • assertMatchesXmlSnapshot($actual, $id)
  • assertMatchesYamlSnapshot($actual, $id)
  • assertMatchesImageSnapshot($actual, $threshold, $includeAa, $id)

Snapshot Testing 101

Let's do a snapshot assertion for a simple string, "foo".

php
public function test_it_is_foo() {
    $this->assertMatchesSnapshot('foo');
}

The first time the assertion runs, it doesn't have a snapshot to compare the string with. The test runner generates a new snapshot and marks the test as incomplete.

> ./vendor/bin/phpunit

There was 1 incomplete test:

1) ExampleTest::test_it_matches_a_string
Snapshot created for ExampleTest__test_it_matches_a_string__1

OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 0, Incomplete: 1.

Snapshot ids are generated based on the test and testcase's names. Basic snapshots return a plain text or YAML representation of the actual value.

txt
foo

Let's rerun the test. The test runner will see that there's already a snapshot for the assertion and do a comparison.

> ./vendor/bin/phpunit

OK (1 test, 1 assertion)

If we change actual value to "bar", the test will fail because the snapshot still returns "foo".

php
public function test_it_is_foo() {
    $this->assertMatchesSnapshot('bar');
}
> ./vendor/bin/phpunit

1) ExampleTest::test_it_matches_a_string
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'foo'
+'bar'

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

When we expect a changed value, we need to tell the test runner to update the existing snapshots instead of failing the test. The package ships a wrapper binary that runs PHPUnit with the right environment variable set:

> ./vendor/bin/update-snapshots

OK (1 test, 1 assertion)

vendor/bin/update-snapshots accepts the same arguments as phpunit, so you can target a specific test:

> ./vendor/bin/update-snapshots tests/OrderTest.php

As a result, our snapshot file returns "bar" instead of "foo".

txt
bar

You can also set the UPDATE_SNAPSHOTS environment variable directly. This is useful in CI, or when you want to define a Composer script for your project.

> UPDATE_SNAPSHOTS=true ./vendor/bin/phpunit

A common pattern is to add an update-snapshots script to your project's composer.json:

json
{
    "scripts": {
        "update-snapshots": "UPDATE_SNAPSHOTS=true vendor/bin/phpunit"
    }
}

You can then run composer update-snapshots (and pass extra arguments via composer update-snapshots -- tests/OrderTest.php).

Why not phpunit -d --update-snapshots?

Earlier versions of this package documented phpunit -d --update-snapshots as the way to enable updates. That syntax abuses PHPUnit's -d flag, which is designed to set php.ini values. Since PHPUnit 12.5.12, failed ini_set() calls produce a visible Failed to set "--update-snapshots=1" warning, surfacing the misuse. The wrapper binary and the environment variable replace that approach. The legacy CLI argument still works for backwards compatibility, but produces the warning on PHPUnit 12.5.12 and later.

File snapshots

The MatchesSnapshots trait offers two ways to assert that a file is identical to the snapshot that was made the first time the test was run:

The assertMatchesFileHashSnapshot($filePath) assertion asserts that the hash of the file passed into the function and the hash saved in the snapshot match. This assertion is fast and uses very little disk space. The downside of this assertion is that there is no easy way to see how the two files differ if the test fails.

The assertMatchesFileSnapshot($filePath) assertion works almost the same way as the file hash assertion, except that it actually saves the whole file in the snapshots directory. If the assertion fails, it places the failed file next to the snapshot file so they can easily be manually compared. The persisted failed file is automatically deleted when the test passes. This assertion is most useful when working with binary files that should be manually compared like images or pdfs.

Image snapshots

The assertImageSnapshot requires the spatie/pixelmatch-php package to be installed.

This assertion will pass if the given image is nearly identical to the snapshot that was made the first time the test was run. You can customize the threshold by passing a second argument to the assertion. Higher values will make the comparison more sensitive. The threshold should be between 0 and 1.

php
$this->assertMatchesImageSnapshot($imagePath, 0.1);

Named Snapshots

By default, snapshots are identified by an auto-incrementing number. You can pass an explicit $id to any assertion method to use a named snapshot instead:

php
$this->assertMatchesJsonSnapshot($order->toJson(), 'order-json');
$this->assertMatchesTextSnapshot($output, 'cli-output');

Named snapshots use a s- prefix internally to avoid collisions with auto-incremented ids. Named and auto-incremented snapshots can be mixed freely within a single test — named snapshots don't affect the auto-increment counter.

Customizing Snapshot Ids and Directories

Snapshot ids are generated via the getSnapshotId method on the MatchesSnapshot trait. Override the method to customize the id. By default, a snapshot id exists of the test name, the test case name and an incrementing value, e.g. Test__my_test_case__1.

Example: Replacing the __ Delimiter With --

php
protected function getSnapshotId(): string
{
    return (new ReflectionClass($this))->getShortName().'--'.
        $this->name().'--'.
        $this->snapshotIncrementor;
}

By default, snapshots are stored in a __snapshots__ directory relative to the test class. This can be changed by overriding the getSnapshotDirectory method.

Example: Renaming the __snapshots__ directory to snapshots

php
protected function getSnapshotDirectory(): string
{
    return dirname((new ReflectionClass($this))->getFileName()).
        DIRECTORY_SEPARATOR.
        'snapshots';
}

Using specific Drivers

The driver used to serialize the data can be specificied as second argument of the assertMatchesSnapshot method, so you can pick one that better suits your needs:

php
use Spatie\Snapshots\Drivers\JsonDriver;
use Spatie\Snapshots\MatchesSnapshots;

class OrderTest
{
    use MatchesSnapshots;

    public function test_snapshot_with_json_driver()
    {
        $order = new Order(1);

        $this->assertMatchesSnapshot($order->toJson(), new JsonDriver());
    }
}

Writing Custom Drivers

Drivers ensure that different types of data can be serialized and matched in their own way. A driver is a class that implements the Spatie\Snapshots\Driver interface, which requires three method implementations: serialize, extension and match.

Let's take a quick quick look at the JsonDriver.

…
  • The serialize method returns a string which will be written to the snapshot file. In the JsonDriver, we'll decode and re-encode the json string to ensure the snapshot has pretty printing.
  • We want to save json snapshots as json files, so we'll use json as their file extension.
  • When matching the expected data with the actual data, we want to use PHPUnit's built in json assertions, so we'll call the specific assertJsonStringEqualsJsonString method.

Drivers can be used by passing them as assertMatchesSnapshot's second argument.

php
$this->assertMatchesSnapshot($something->toYaml(), new MyYamlDriver());

Usage in CI

When running your tests in Continuous Integration you would possibly want to disable the creation of snapshots, so missing snapshots cause the build to fail instead of being silently created.

Set the CREATE_SNAPSHOTS=false environment variable when invoking PHPUnit:

bash
> CREATE_SNAPSHOTS=false ./vendor/bin/phpunit

1) ExampleTest::test_it_matches_a_string
Snapshot "ExampleTest__test_it_matches_a_string__1.txt" does not exist.
You can enable snapshot creation by running `vendor/bin/phpunit` directly, or by unsetting the `CREATE_SNAPSHOTS=false` environment variable.
json
{
    "scripts": {
        "test:ci": "CREATE_SNAPSHOTS=false vendor/bin/phpunit"
    }
}

Earlier versions of this package documented phpunit -d --without-creating-snapshots. Since PHPUnit 12.5.12, that syntax produces a Failed to set "--without-creating-snapshots=1" test runner warning because it abuses PHPUnit's -d flag (which is designed for php.ini values). The CREATE_SNAPSHOTS=false environment variable replaces that approach.

Usage with parallel testing

If you want to run your test in parallel with a tool like Paratest, or with the php artisan test --parallel command of Laravel, you will have to use the environment variables.

bash
> CREATE_SNAPSHOTS=false php artisan test --parallel

1) ExampleTest::test_it_matches_a_string
Snapshot "ExampleTest__test_it_matches_a_string__1.txt" does not exist.
You can enable snapshot creation by running `vendor/bin/phpunit` directly, or by unsetting the `CREATE_SNAPSHOTS=false` environment variable.

A no

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPphpphpunitsnapshot-testingtesting

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category测试质量
PricingOpen source

> Related tools

J
Jest
JavaScript 测试框架
P
Playwright
现代端到端测试框架
E
eslint-plugin-test-selectors
Enforces that data-test-id attributes are added to interactive DOM elements (JSX) to help with UI testing. JSX only.