Reputation: 2261
I'm wanting to write a test to create a user then test if the user is shows within the Users API index collection using the route.
I've read through the documentation on writing REST API Tests with Laravel and PHPUnit. I'm having a hard time getting the assertJson
to pass as it's returning the following error:
Failed asserting that an array has the subset Array &0 (
'name' => 'Buck Trantow V'
'email' => '[email protected]'
'username' => 'hhudson'
).
--- Expected
+++ Actual
@@ @@
array (
),
),
- 'name' => 'Buck Trantow V',
- 'email' => '[email protected]',
- 'username' => 'hhudson',
)
Test:
public function testUserIndex()
{
$user = factory(User::class)->create();
$response = $this
->actingAs($user, 'api')
->json('GET', '/api/users')
->assertStatus(200);
$response
->assertJson([
'name' => $user->name,
'email' => $user->email,
'username' => $user->username,
]);
}
Route / User Controller:
Route::resource('users', 'UserController');
UserController:
public function index()
{
return User::all();
}
Upvotes: 2
Views: 3201
Reputation: 2261
Posting here for anyone that needs it.. I've found that assertJsonFragment
works for this scenario.
$response
->assertJsonFragment([
'name' => $user->name,
'email' => $user->email,
'username' => $user->username,
]);
Upvotes: 3