1

我目前正在开发一项功能,用户可以跨设备查看他们的所有会话。现在,当尝试对此功能进行功能测试时,我正在执行以下操作:(注意:我正在使用 Inertia 并且有一些测试宏)

  • 创建迁移:

php artisan session:table

  • 编辑phpunit.xml

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

  • 在 AppServiceProvider 中共享 prop:
Inertia::share([
    // a few other props
    'auth' => [
        'user' => [
            // a few other props
            'sessions' => DB::table('sessions')->whereUserId(auth()->user()->id)->get(),
        ],
    ],
]);
  • 写一个测试
// 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
    });

我不明白的是,当我sessions在浏览器中手动测试道具(使用 Vue devtools 检查)时,我确实得到了所有会话并且数组不为空。

现在,当尝试在同一个测试中再次请求页面时,我得到了会话......

$this->signIn($user);

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

$this->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"
            ]
        ]
    });

实际功能有效,但测试不是绿色的。谁能解释为什么会这样?我花了几个小时在谷歌上搜索,但没有找到适合我的解决方案。谢谢

4

0 回答 0