2

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.

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.