PHP code example of bmarsaud / phpunit-snapshot-assertions

1. Go to this page and download the library: Download bmarsaud/phpunit-snapshot-assertions library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bmarsaud / phpunit-snapshot-assertions example snippets


use Spatie\Snapshots\MatchesSnapshots;

class OrderTest
{
    use MatchesSnapshots;

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

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

$orderId = new Order(2); // Regression! Was `1`

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

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

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

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

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());
    }
}

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);
    }
}

$this->assertMatchesSnapshot($something->toYaml(), new MyYamlDriver());
txt
tests/**/__snapshots__/** text eol=lf