Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bencarter78@hotmail.com's avatar

Trying to understand why assertJson fails

Hello

I was hoping someone could help me understand why my test would be failing. The failure message says

Unable to find JSON: 

[{
    "sectors": [
        {
            "code": "OM326",
            "name": "Et Rerum",
            "department_id": 1,
            "updated_at": "2017-12-07 13:01:12",
            "created_at": "2017-12-07 13:01:12",
            "id": 1,
            "title": "[OM326] Et Rerum"
        }
    ]
}]

within response JSON:

[{
    "ok": true,
    "data": {
        "sectors": [
            {
                "id": 1,
                "code": "OM326",
                "name": "Et Rerum",
                "department_id": "1",
                "created_at": "2017-12-07 13:01:12",
                "updated_at": "2017-12-07 13:01:12",
                "deleted_at": null,
                "title": "[OM326] Et Rerum"
            }
        ]
    }
}].

My test for this is

$sectors = factory(Sector::class)->create();

$this->json('GET', route('api.apply.sectors.index'))->assertJson(['sectors' => [$sectors]]);

And my endpoint is

public function index()
    {
        return response()->json([
        'ok' => true,
            'data' => [
                'sectors' => Sector::all(),
            ],
        ], 200);
    }

I'm not understanding why it can't find the array. Can someone help?

Thanks

0 likes
3 replies
bencarter78@hotmail.com's avatar

@cruskai Sorry I have just noticed in my controller I had left $this->response() in, that actually calls response()->json(). I'll update my original post.

Chris_Ruskai's avatar
Level 4

@bencarter78 Ah okay. It also looks like your expected JSON is an object that is within an array. Sectors in your response looks like its in an object not an array. Does removing the outermost brackets in your expected value like this make the test work?

{
    "sectors": [
        {
            "code": "OM326",
            "name": "Et Rerum",
            "department_id": 1,
            "updated_at": "2017-12-07 13:01:12",
            "created_at": "2017-12-07 13:01:12",
            "id": 1,
            "title": "[OM326] Et Rerum"
        }
    ]
}

Please or to participate in this conversation.