Search code examples
phparrayslaravelunit-testingmultidimensional-array

Test multidimensional array with Laravel and Pest


I have a little problem when I want to test an array in my unit test.

I want to test both structure and type of keys, but I don't know how to process it (I tried, I promise!).

Here is the json input:

{
    "success": true,
    "data": [
        {
            "id": 1,
            "domains_id": 1,
            "sub": "",
            "type": "",
            "ip_or_fqdn": "",
            "created_at": "2022-05-14T08:30:18.000000Z",
            "updated_at": "2022-05-14T08:30:18.000000Z"
        }
    ],
    "message": "Domain retrieved successfully."
}

And there is, for the moment, the test:

it('fetch zone entries [GET] with json response and check response type', function () {

    TestCase::initDatabase();

    Passport::actingAs(
        User::factory()->make()
    );

    $response = $this->withHeaders([
            'Accept' => 'application/json'
        ])
        ->json('GET', '/api/zone')
        ->assertStatus(200)
        ->assertJson(function (AssertableJson $json) {
            $json->has('success')
                 ->whereType('success', 'boolean')
                 ->has('data')
                 ->whereType('data', 'array')
                 ->has('message')
                 ->whereType('message', 'string');
    });

    TestCase::resetDatabase();
});

I want to test the "data" array keys/values with this process and, of course, in this Closure; but is it possible?


Solution

  • You may use dot notation, for instance

    ->assertJson(fn (AssertableJson $json) =>
        $json->has('data.id')
            ->where('data.id', 1)
            ->missing('data.x')
        );