• Stars
    star
    584
  • Rank 73,509 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 7 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A way to test without writing actual test cases

Snapshot testing with PHPUnit

Latest Version on Packagist Software License run-tests Total Downloads

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.

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!

$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:

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)
  • assertMatchesFileHashSnapshot($actual)
  • assertMatchesFileSnapshot($actual)
  • assertMatchesHtmlSnapshot($actual)
  • assertMatchesJsonSnapshot($actual)
  • assertMatchesObjectSnapshot($actual)
  • assertMatchesTextSnapshot($actual)
  • assertMatchesXmlSnapshot($actual)
  • assertMatchesYamlSnapshot($actual)

Snapshot Testing 101

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

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.

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

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. This is possible by adding a-d --update-snapshots flag to the phpunit command, or setting the UPDATE_SNAPSHOTS env var to true.

> ./vendor/bin/phpunit -d --update-snapshots

OK (1 test, 1 assertion)

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

bar

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.

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

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

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:

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.

namespace Spatie\Snapshots\Drivers;

use PHPUnit\Framework\Assert;
use Spatie\Snapshots\Driver;
use Spatie\Snapshots\Exceptions\CantBeSerialized;

class JsonDriver implements Driver
{
    public function serialize($data): string
    {
        if (! is_string($data)) {
            throw new CantBeSerialized('Only strings can be serialized to json');
        }

        return json_encode(json_decode($data), JSON_PRETTY_PRINT).PHP_EOL;
    }

    public function extension(): string
    {
        return 'json';
    }

    public function match($expected, $actual)
    {
        Assert::assertJsonStringEqualsJsonString($actual, $expected);
    }
}
  • 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.

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

By using the --without-creating-snapshots parameter or by setting the CREATE_SNAPSHOTS env var to false, PHPUnit will fail if the snapshots don't exist.

> ./vendor/bin/phpunit -d --without-creating-snapshots

1) ExampleTest::test_it_matches_a_string
Snapshot "ExampleTest__test_it_matches_a_string__1.txt" does not exist.
You can automatically create it by removing the `CREATE_SNAPSHOTS=false` env var, or `-d --no-create-snapshots` of PHPUnit's CLI arguments.

Usage with parallel testing

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

> 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 automatically create it by removing the `CREATE_SNAPSHOTS=false` env var, or `-d --no-create-snapshots` of PHPUnit's CLI arguments.

A note for Windows users

Windows users should configure their line endings in .gitattributes.

# Snapshots used in tests hold serialized data and their line ending should be left unchanged
tests/**/__snapshots__/** binary

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more information.

More Repositories

1

laravel-permission

Associate users with roles and permissions
PHP
11,600
star
2

laravel-medialibrary

Associate files with Eloquent models
PHP
5,427
star
3

laravel-backup

A package to backup your Laravel app
PHP
5,337
star
4

laravel-activitylog

Log activity inside your Laravel app
PHP
5,128
star
5

browsershot

Convert HTML to an image, PDF or string
PHP
4,434
star
6

laravel-query-builder

Easily build Eloquent queries from API requests
PHP
3,675
star
7

laravel-analytics

A Laravel package to retrieve pageviews and other data from Google Analytics
PHP
2,948
star
8

image-optimizer

Easily optimize images using PHP
PHP
2,450
star
9

async

Easily run code asynchronously
PHP
2,401
star
10

crawler

An easy to use, powerful crawler implemented in PHP. Can execute Javascript.
PHP
2,400
star
11

laravel-responsecache

Speed up a Laravel app by caching the entire response
PHP
2,248
star
12

data-transfer-object

Data transfer objects with batteries included
PHP
2,220
star
13

laravel-translatable

Making Eloquent models translatable
PHP
2,030
star
14

laravel-sitemap

Create and generate sitemaps with ease
PHP
2,011
star
15

dashboard.spatie.be

The source code of dashboard.spatie.be
PHP
1,940
star
16

laravel-fractal

An easy to use Fractal wrapper built for Laravel and Lumen applications
PHP
1,845
star
17

package-skeleton-laravel

A skeleton repository for Spatie's Laravel Packages
PHP
1,714
star
18

laravel-collection-macros

A set of useful Laravel collection macros
PHP
1,602
star
19

laravel-newsletter

Manage Mailcoach and MailChimp newsletters in Laravel
PHP
1,570
star
20

period

Complex period comparisons
PHP
1,515
star
21

checklist-going-live

The checklist that is used when a project is going live
1,489
star
22

laravel-tags

Add tags and taggable behaviour to your Laravel app
PHP
1,454
star
23

opening-hours

Query and format a set of opening hours
PHP
1,340
star
24

schema-org

A fluent builder Schema.org types and ld+json generator
PHP
1,284
star
25

eloquent-sortable

Sortable behaviour for Eloquent models
PHP
1,268
star
26

laravel-cookie-consent

Make your Laravel app comply with the crazy EU cookie law
PHP
1,268
star
27

laravel-sluggable

An opinionated package to create slugs for Eloquent models
PHP
1,236
star
28

laravel-searchable

Pragmatically search through models and other sources
PHP
1,217
star
29

pdf-to-image

Convert a pdf to an image
PHP
1,207
star
30

once

A magic memoization function
PHP
1,159
star
31

laravel-honeypot

Preventing spam submitted through forms
PHP
1,134
star
32

laravel-mail-preview

A mail driver to quickly preview mail
PHP
1,134
star
33

laravel-image-optimizer

Optimize images in your Laravel app
PHP
1,121
star
34

laravel-google-calendar

Manage events on a Google Calendar
PHP
1,119
star
35

laravel-settings

Store strongly typed application settings
PHP
1,100
star
36

regex

A sane interface for php's built in preg_* functions
PHP
1,097
star
37

laravel-data

Powerful data objects for Laravel
PHP
1,073
star
38

image

Manipulate images with an expressive API
PHP
1,064
star
39

array-to-xml

A simple class to convert an array to xml
PHP
1,056
star
40

laravel-multitenancy

Make your Laravel app usable by multiple tenants
PHP
1,020
star
41

laravel-uptime-monitor

A powerful and easy to configure uptime and ssl monitor
PHP
997
star
42

db-dumper

Dump the contents of a database
PHP
987
star
43

laravel-model-states

State support for models
PHP
968
star
44

laravel-view-models

View models in Laravel
PHP
963
star
45

simple-excel

Read and write simple Excel and CSV files
PHP
930
star
46

laravel-web-tinker

Tinker in your browser
JavaScript
925
star
47

laravel-webhook-client

Receive webhooks in Laravel apps
PHP
908
star
48

laravel-db-snapshots

Quickly dump and load databases
PHP
889
star
49

laravel-mix-purgecss

Zero-config Purgecss for Laravel Mix
JavaScript
887
star
50

laravel-schemaless-attributes

Add schemaless attributes to Eloquent models
PHP
880
star
51

blender

The Laravel template used for our CMS like projects
PHP
879
star
52

calendar-links

Generate add to calendar links for Google, iCal and other calendar systems
PHP
877
star
53

laravel-webhook-server

Send webhooks from Laravel apps
PHP
870
star
54

laravel-menu

Html menu generator for Laravel
PHP
854
star
55

phpunit-watcher

A tool to automatically rerun PHPUnit tests when source code changes
PHP
831
star
56

laravel-failed-job-monitor

Get notified when a queued job fails
PHP
826
star
57

laravel-model-status

Easily add statuses to your models
PHP
818
star
58

laravel-schedule-monitor

Monitor scheduled tasks in a Laravel app
PHP
800
star
59

form-backend-validation

An easy way to validate forms using back end logic
JavaScript
800
star
60

temporary-directory

A simple class to work with a temporary directory
PHP
796
star
61

laravel-feed

Easily generate RSS feeds
PHP
789
star
62

laravel-server-monitor

Don't let your servers just melt down
PHP
769
star
63

fork

A lightweight solution for running code concurrently in PHP
PHP
751
star
64

enum

Strongly typed enums in PHP supporting autocompletion and refactoring
PHP
737
star
65

laravel-tail

An artisan command to tail your application logs
PHP
726
star
66

valuestore

Easily store some values
PHP
722
star
67

laravel-package-tools

Tools for creating Laravel packages
PHP
722
star
68

laravel-event-sourcing

The easiest way to get started with event sourcing in Laravel
PHP
716
star
69

geocoder

Geocode addresses to coordinates
PHP
709
star
70

pdf-to-text

Extract text from a pdf
PHP
707
star
71

ssh

A lightweight package to execute commands over an SSH connection
PHP
696
star
72

menu

Html menu generator
PHP
688
star
73

laravel-url-signer

Create and validate signed URLs with a limited lifetime
PHP
685
star
74

ssl-certificate

A class to validate SSL certificates
PHP
675
star
75

laravel-route-attributes

Use PHP 8 attributes to register routes in a Laravel app
PHP
674
star
76

laravel-validation-rules

A set of useful Laravel validation rules
PHP
663
star
77

url

Parse, build and manipulate URL's
PHP
659
star
78

laravel-html

Painless html generation
PHP
654
star
79

laravel-health

Check the health of your Laravel app
PHP
648
star
80

laravel-event-projector

Event sourcing for Artisans 📽
PHP
642
star
81

laravel-server-side-rendering

Server side rendering JavaScript in your Laravel application
PHP
636
star
82

vue-tabs-component

An easy way to display tabs with Vue
JavaScript
626
star
83

macroable

A trait to dynamically add methods to a class
PHP
621
star
84

laravel-csp

Set content security policy headers in a Laravel app
PHP
614
star
85

laravel-blade-javascript

A Blade directive to export variables to JavaScript
PHP
608
star
86

laravel-cors

Send CORS headers in a Laravel application
PHP
607
star
87

laravel-translation-loader

Store your translations in the database or other sources
PHP
602
star
88

vue-table-component

A straight to the point Vue component to display tables
JavaScript
591
star
89

activitylog

A very simple activity logger to monitor the users of your website or application
PHP
586
star
90

http-status-check

CLI tool to crawl a website and check HTTP status codes
PHP
584
star
91

laravel-queueable-action

Queueable actions in Laravel
PHP
584
star
92

laravel-short-schedule

Schedule artisan commands to run at a sub-minute frequency
PHP
579
star
93

laravel-onboard

A Laravel package to help track user onboarding steps
PHP
579
star
94

freek.dev

The sourcecode of freek.dev
PHP
571
star
95

server-side-rendering

Server side rendering JavaScript in a PHP application
PHP
568
star
96

laravel-pdf

Create PDF files in Laravel apps
PHP
563
star
97

string

String handling evolved
PHP
558
star
98

ray

Debug with Ray to fix problems faster
PHP
540
star
99

laravel-http-logger

Log HTTP requests in Laravel applications
PHP
538
star
100

laravel-blade-x

Use custom HTML components in your Blade views
PHP
533
star