Search code examples
jsontestinglaravel-5phpunitassert

Laravel AssertJsonCount on a nested array


How can I call assertJsonCount using an indexed, nested array?

In my test, the following JSON is returned:

[[{"sku":"P09250"},{"sku":"P03293"}]]

But attempting to use assertJsonCount returns the following error:

$response->assertJsonCount(2);

// Failed asserting that actual size 1 matches expected size 2.

Solution

  • This may or may not be specific to Laravel. Although a Laravel helper is involved, this issue may occur elsewhere.

    assertJsonCount utilises the PHPUnit function PHPUnit::assertCount which uses a laravel helper data_get, which has the following signature:

    /**
     * Get an item from an array or object using "dot" notation.
     *
     * @param  mixed   $target
     * @param  string|array|int  $key
     * @param  mixed   $default
     * @return mixed
     */
    function data_get($target, $key, $default = null)
    {
        if (is_null($key)) {
            return $target;
        }
        ...
    

    We can see that the JSON returned is a nested array, so logically we should pass in a key of 0.

    $response->assertJsonCount($expectedProducts->count(), '0');
    

    However this will be ignored as assertCount function checks if a key has been passed using is_null.

    To overcome this, we can count all children of 0:

    $response->assertJsonCount($expectedProducts->count(), '0.*');
    

    This will produce the desired result.