Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Empty json objects encoded as arrays #73

Open
mintbridge opened this issue Oct 2, 2019 · 3 comments · May be fixed by #74

Comments

@mintbridge
Copy link

commented Oct 2, 2019

Hi,

When an empty object is used it is been serialised and snapshotted as an array, for example this will fail once the snapshot is created:

    public function testJsonSnapshot()
    {
        $json = json_encode((object) [
            'data' => [
                'objectData' => (object)[]
            ]
        ]);

        // dump($json);
        // {"data":{"objectData":{}}}

        $this->assertMatchesJsonSnapshot($json);
        // snapshot contents
        /*
        {
            "data": {
                "objectData": []
            }
        }
        */

    }

basically [] in the snapshot vs {} in the $json variable

Paul

@mintbridge

This comment has been minimized.

Copy link
Author

commented Oct 2, 2019

pretty sure its because of JSON_PRETTY_PRINT

@mintbridge

This comment has been minimized.

Copy link
Author

commented Oct 2, 2019

and this might be the answer but not sure where it should be fixed? https://www.php.net/manual/en/json.constants.php#constant.json-force-object

@mintbridge

This comment has been minimized.

Copy link
Author

commented Oct 2, 2019

ok, its the true parameter of this line https://github.com/spatie/phpunit-snapshot-assertions/blob/master/src/Drivers/JsonDriver.php#L14

however removing that causes an error with json that has an object at the root level because of https://github.com/spatie/phpunit-snapshot-assertions/blob/master/src/Drivers/JsonDriver.php#L17

so its fixable with something like:

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

        if (! is_array($data) && !is_object($data)) {
            throw new CantBeSerialized('Only strings can be serialized to json');
        }

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

but that will be a breaking change for any existing snapshots, and i dont know what the original context of limiting what can be serialized to json was?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.