You need to use response()->json() for JSON responses. It sets your Content-Type header to application/json and converts your data structures.
Dec 7, 2017
3
Level 14
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
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.