spatie / phpunit-snapshot-assertions

A way to test without writing actual test cases
https://spatie.be/courses/testing-laravel-with-pest/snapshot-testing
MIT License
642 stars 71 forks source link

Add ability to configure JsonDriver and ObjectDriver #135

Closed alshenetsky closed 2 years ago

alshenetsky commented 2 years ago

This is very handy feature when comparing diffs between snapshots with unicode symbols

baijunyao commented 2 years ago

Aha, looks like we're doing some duplication. đŸ˜‚ #131

Stevemoretz commented 2 years ago

it wasn't intended to (I saw this pull request after I made mine), but my PR probably have fixed one of your issue as well (the match part shouldn't matter anymore, you need to put the option for printing now only, that option could be also provided via a callback function so the user can whatever they want and return it, then you can save it.) check it out : https://github.com/spatie/phpunit-snapshot-assertions/pull/138

eg:

    private ?\Closure $manualEncode;
    public function __construct(\Closure $manualEncode = null) {
        if($manualEncode){
            $this->manualEncode = $manualEncode;
        }
    }

    public function serialize($data): string
    {
        if (is_string($data)) {
            $data = json_decode($data);
        }

        if (is_resource($data)) {
            throw new CantBeSerialized('Resources can not be serialized to json');
        }

        if($this->manualEncode){
            return ($this->manualEncode)($data);
        }

        return json_encode($data, JSON_PRETTY_PRINT)."\n";
    }

Or maybe even better : (after I thought more about your case)

    private $jsonEncodeOption = JSON_PRETTY_PRINT;
    public function __construct($jsonEncodeOption = null) {
        if($jsonEncodeOption){
            $this->jsonEncodeOption = $jsonEncodeOption;
        }
    }

    public function serialize($data): string
    {
        if (is_string($data)) {
            $data = json_decode($data);
        }

        if (is_resource($data)) {
            throw new CantBeSerialized('Resources can not be serialized to json');
        }

        return json_encode($data, $this->jsonEncodeOption)."\n";
    }

Combined with my PR everything should be backwards compatible.

spatie-bot commented 2 years ago

Dear contributor,

because this pull request seems to be inactive for quite some time now, I've automatically closed it. If you feel this pull request deserves some attention from my human colleagues feel free to reopen it.