Testing keys of a JSON API response

Published on 2022-06-28 • Modified on 2022-06-28

In this snippet, we see how to test the presence of keys in a JSON API response. We can use the PHPUnit assertEqualsCanonicalizing() assertion. As you can see, the order of the keys doesn't matter as the array is normalized before the comparison is made.

     * @see ApiController::stats()
    public function testStats(): void
        $stats = $this->repo->getArticlesCount();
        $client = self::createClient();
        $client->request('GET', '/stats');
        self::assertResponseHeaderSame('content-type', 'application/json');
        self::assertEqualsCanonicalizing(['posts', 'snippets'], array_keys($stats));
        self::assertEqualsCanonicalizing(['snippets', 'posts'], array_keys($stats));
            'posts' => $stats['posts'],
            'snippets' => $stats['snippets'],

  Read the doc  Random snippet

  Work with me!