Api-platform how to use assertJsonContains with dynamic data in test class?

Viewed 24

Sometime, the json response has some properties that have "dynamic data", like id, createdAt below:

  $this->assertJsonContains(
            [
                "data" => [
                    "id" => "@integer",
                    "type" => "resource-category",
                    "attributes" => [
                        "name" => "Office",
                        "slug" => "office",
                        "createdAt => "@string"
                    ]
                ]
            ]
        );

So I would like to expect these field same the type like integer, string,... How could I do that?

1 Answers

API-Platform will generate a schema for your operations, i.e. describe what the output should look like, which fields it should have and what the expected types are. You can store this schema and then test against it using something like justinrainbow/json-schema, which should come with api-platform anyway. Here is the basic example from the docs, which you can use for your test:


<?php

$data = json_decode(file_get_contents('data.json'));

// Validate
$validator = new JsonSchema\Validator;
$validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]);

self::assertIsTrue($validator->isValid());

The thing you need to look out for, is that you can’t use the automatically generated schema directly. Your test will always fit the output as the schema is generated from it.

Related