mercredi 11 mars 2020

Laravel database sessions in phpunit tests

I'm currently working on a feature where users can view all their sessions across devices. Now when trying to feature test this functionality, I´m doing the following: (Note: I´m using Inertia.js and have a few test macros)

  • Create the migration:

php artisan session:table

  • Edit phpunit.xml:

<server name="SESSION_DRIVER" value="database"/>

  • Share the prop in the AppServiceProvider:
Inertia::share([
    // a few other props
    'auth' => [
        'user' => [
            // a few other props
            'sessions' => DB::table('sessions')->whereUserId(auth()->user()->id)->get(),
        ],
    ],
]);
  • Write a test
// The test class is set up correctly with the RefreshDatabase trait

$user = factory(User::class)->create();
$this->signIn($user) // helper for actingAs()
    ->get(route('sessions.index'))
    ->assertPropIs('auth.user.sessions', function ($sessions) use ($user) {
        // gets the 'sessions' page prop and passes the prop value to my callback here
        $userSessions = DB::table('sessions')->whereUserId($user->id)->toArray();
        return $sessions === $userSessions;
        // The problem here is that $sessions is an empty array :(
        // BUT $userSessions does contain the active session of $user
    });

What I don´t understand is that when I manually test the sessions prop in the browser (inspecting with Vue devtools) I do get all sessions back and the array is not empty.

Now, when trying to request the page again in the same test, I get the session...

$this->signIn($user)
    ->get(route('sessions.index'))
    ->assertPropIs('auth.user.sessions', function ($sessions) {
        dd($sessions); // returns an empty array
    });

$this->signIn($user)
    ->get(route('sessions.index'))
    ->assertPropIs('auth.user.sessions', function ($sessions) {
        dd($sessions); // Returns the following
        array:1 [
            0 => array:6 [
                "id" => "BaIZnSNxjVEEtJyeD3uLKrreG9U0bbSjc8kQreGo"
                "user_id" => "1"
                "ip_address" => "127.0.0.1"
                "user_agent" => "Symfony"
                "payload" => "YTozOntzOjY6Il90b2tlbiI7czo0MDoiZHptd2V4ZkVwcndaRERaQTNDSmdVVEN1OUpNcXRqQlN0Tnhna0pjYiI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MzU6Imh0dHBzOi8vbGltYm9zZXJ2aWNlLnRlc3QvZGFzaGJvYXJkIjt9czo2OiJfZmxhc2giO2E6Mjp7czozOiJvbGQiO2E6MDp7fXM6MzoibmV3IjthOjA6e319fQ=="
                "last_activity" => "1583916772"
            ]
        ]
    });

The actual functionality works, but the tests are not green. Can anyone explain why this happens? I´ve spent hours of googling and didn´t find a solution that worked for me. Thanks

Aucun commentaire:

Enregistrer un commentaire