Reputation: 3962
I have the following controller on my Laravel
application:
class ProjectController extends Controller {
...
public function index() {
$projects = Project::where('is_completed', false)
->orderBy('created_at', 'desc')
->withCount(['tasks' => function ($query) {
$query->where('is_completed', false);
}])->get();
return response()->json($projects);
}
...
}
which is referenced by the following route:
Route::get('projects', 'ProjectController@index');
When I go to the url: http://localhost:8000/api/projects
I get:
[
{
"id": 2,
"name": "Project 02 Title",
"description": "Project 02 Description",
"is_completed": 0,
"created_at": "2018-10-13 16:23:28",
"updated_at": "2018-10-13 16:23:28",
"tasks_count": 0
},
{
"id": 1,
"name": "Project 01 Title",
"description": "Project 01 Description",
"is_completed": 0,
"created_at": "2018-10-13 16:22:52",
"updated_at": "2018-10-13 16:22:52",
"tasks_count": 0
}
]
Also, I have the following test file:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ProjectTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$response = $this->get('/');
// this is not working:
// $response->assertJson([ 0 => [ 'name' => 'Project 02 Title' ] ]);
}
}
?>
What I want to do on testExample()
is to check if the name
member of the first element on the output array (in JSON
format) has the string value: Project 02 Title
.
Any idea on how to achieve this?
Thanks!
Upvotes: 1
Views: 4345
Reputation: 111829
If you know the exact array element you're looking for, you can test individual attributes; for example:
$json = $reponse->json();
$this->assertSame('Project 02 Title', $json[0]['name']);
Or in case you want to test the JSON structure you can use:
$response->assertJsonFragment([
'name' => 'Project 02 Title'
]);
Upvotes: 2
Reputation: 27
Check your test again, you are not visiting the right endpoint:
$response = $this->get('/');
That should probably look more like this:
$response = $this->get('/api/projects');
Your test should work, it looks okay.
Upvotes: -2