dimanche 25 novembre 2018

Laravel Testing Collection JSON Response with assertJson

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' => 'marianne.leffler@example.org'
    'username' => 'hhudson'
).
--- Expected
+++ Actual
@@ @@
     array (
     ),
   ),
-  'name' => 'Buck Trantow V',
-  'email' => 'marianne.leffler@example.org',
-  '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();
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire