PHP code example of chqthomas / approval-tests

1. Go to this page and download the library: Download chqthomas/approval-tests 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/ */

    

chqthomas / approval-tests example snippets


composer 

use ChqThomas\ApprovalTests\Approvals;

public function testSimpleString(): void 
{
    Approvals::verify("Hello World");
}

public function testArray(): void 
{
    $data = [
        'name' => 'John Doe',
        'age' => 30,
        'roles' => ['admin', 'user']
    ];
    Approvals::verify($data);
}

public function testHtml(): void 
{
    $html = '<div>Hello <span>World</span></div>';
    Approvals::verifyHtml($html);
}

public function testJson(): void 
{
    $json = '{"name":"John","age":30}';
    Approvals::verifyJson($json); // Automatically formatted
}

public function testXml(): void 
{
    $xml = '<?xml version="1.0"

public function testCsv(): void 
{
    $csv = "name,age\nJohn,30\nJane,25";
    Approvals::verifyCsv($csv);
}

public function testBinaryFile(): void 
{
    Approvals::verifyBinaryFile('path/to/image.png', 'png');
}

/**
 * @dataProvider provideTestData
 */
public function testWithDataProvider(array $data, string $expected): void 
{
    $result = processData($data);
    Approvals::verify($result);
}

public static function provideTestData(): array
{
    return [
        'case1' => [['input' => 1], 'output1'],
        'case2' => [['input' => 2], 'output2'],
    ];
}

public function testAllCombinations(): void 
{
    $operations = ['+', '-', '*', '/'];
    $numbers = [1, 2, 3];
    
    Approvals::verifyAllCombinations(
        function($op, $a, $b) {
            switch($op) {
                case '+': return $a + $b;
                case '-': return $a - $b;
                case '*': return $a * $b;
                case '/': return $b != 0 ? $a / $b : 'Division by zero';
            }
        },
        [$operations, $numbers, $numbers]
    );
}



hqThomas\ApprovalTests\Configuration;
use ChqThomas\ApprovalTests\Reporter\DiffReporter;
use ChqThomas\ApprovalTests\Formatter\SymfonyObjectFormatter;

// Global configuration
Configuration::getInstance()
    ->setReporter(new DiffReporter())
    ->setObjectFormatter(new SymfonyObjectFormatter())
    ->setAutoApprove(false);

// Configure default scrubbers for specific formats
Configuration::getInstance()
    ->setDefaultScrubber('json', JsonScrubber::create()
        ->scrubMember('password', 'token')
        ->ignoreMember('sensitive_data'))
    ->setDefaultScrubber('xml', XmlScrubber::create()
        ->addScrubber(RegexScrubber::create([
            '/\d{4}-\d{2}-\d{2}/' => '[DATE]'
        ])));

use ChqThomas\ApprovalTests\Configuration;
use ChqThomas\ApprovalTests\Reporter\DiffReporter;

Configuration::getInstance()->setReporter(new DiffReporter());

use ChqThomas\ApprovalTests\Formatter\SymfonyObjectFormatter;

Configuration::getInstance()->setObjectFormatter(new SymfonyObjectFormatter());

use ChqThomas\ApprovalTests\Namer\EnvironmentAwareNamer;

Configuration::getInstance()->setNamerClass(EnvironmentAwareNamer::class);

Configuration::getInstance()->setAutoApprove(true);

APPROVE_SNAPSHOTS=true vendor/bin/phpunit

public function testJsonScrubbing(): void 
{
    $json = <<<JSON
{
    "user": "John",
    "password": "secret123",
    "timestamp": "2024-01-01T12:00:00",
    "id": "550e8400-e29b-41d4-a716-446655440000"
}
JSON;

    // Default scrubbers automatically handle:
    // - GUIDs (replaced with Guid_1, Guid_2, etc.)
    // - Dates (replaced with DateTimeOffset_1, etc.)
    Approvals::verifyJson($json);
}

public function testJsonIgnoreMember(): void 
{
    $json = <<<JSON
{
    "user": "John",
    "sensitive": {
        "password": "secret123",
        "token": "abc123"
    }
}
JSON;

    Approvals::verifyJson($json, JsonScrubber::create()
        ->ignoreMember('sensitive')); // Member will be removed
}

public function testJsonScrubMember(): void 
{
    $json = <<<JSON
{
    "user": "John",
    "password": "secret123",
    "api_key": "xyz789"
}
JSON;

    Approvals::verifyJson($json, JsonScrubber::create()
        ->scrubMember('password', 'api_key')); // Members will be replaced with "[scrubbed]"
}

public function testXmlScrubbing(): void 
{
    $xml = <<<XML
<?xml version="1.0"

public function testRegexScrubbing(): void 
{
    $json = <<<JSON
{
  "nodes": [
    {"id": "ABC123", "name": "Node1"},
    {"id": "DEF456", "name": "Node2"},
    {"id": "GHI789", "name": "Node3"}
  ]
}
JSON;

    Approvals::verifyJson($json, JsonScrubber::create()
        ->addScrubber(RegexScrubber::create(['/"id": "([A-Z]{3}\d{3})"/' => '"id": "MATCHED"'])));
}

use ChqThomas\ApprovalTests\Scrubber\AbstractScrubber;

class MyScrubber extends AbstractScrubber
{
    public function scrub(string $content): string
    {
        // Apply base scrubbers first (GUIDs, dates)
        $content = $this->scrubGuids($content);
        $content = $this->scrubDates($content);
        
        // Add your custom rules
        $content = preg_replace('/secret-\d+/', '[SECRET]', $content);
        
        // Apply additional scrubbers
        return $this->applyAdditionalScrubbers($content);
    }
}

// Usage
public function testWithCustomScrubber(): void 
{
    $content = "ID: secret-123\nDate: 2024-01-01";
    
    Approvals::verifyWithExtension(
        $content,
        "txt",
        MyScrubber::create()
            ->addScrubber(fn($text) => str_replace('ID:', 'Reference:', $text))
    );
}

use ChqThomas\ApprovalTests\ApprovalMaintenance;

ApprovalMaintenance::cleanUpReceivedFiles(__DIR__ . '/tests/approvals');

$orphanedFiles = ApprovalMaintenance::findOrphanedApprovedFiles(__DIR__ . '/tests');

use ChqThomas\ApprovalTests\Reporter\CliReporter;

Configuration::getInstance()->setReporter(new CliReporter());

use ChqThomas\ApprovalTests\Reporter\DiffReporter;

Configuration::getInstance()->setReporter(new DiffReporter());

use ChqThomas\ApprovalTests\Reporter\CompositeReporter;

$reporter = new CompositeReporter([
    new CliReporter(),
    new DiffReporter()
]);
Configuration::getInstance()->setReporter($reporter);

use ChqThomas\ApprovalTests\Symfony\ApprovalCrawlerAssertionsTrait;

class MyWebTest extends WebTestCase
{
use ApprovalCrawlerAssertionsTrait;

    public function testPageContent(): void
    {
        $client = static::createClient();
        $client->request('GET', '/');
        self::verifySelectorHtml('#main-content');
    }
}