russellxu's avatar

How to test a middleware using request()->user()?

I'm using Sanctum to provides authentication for my app, and I need to test one of my middleware which is:

class ApiAuthenticate
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();   

        if($user->password_changed_at >= $user->currentAccessToken()->created_at){
            throw new UnauthorizedException(['message' => 'Password has been changed, please login again', 'errorCode' => '40108']);
        }

        return $next($request);
    }
}

And my test is:

        /** @test */
        function it_can_deny_request_when_user_changed_password()
        {
			//.....

            $user->update([
                'password' => Hash::make('new_password'),
                'password_changed_at' => now(),
                'name' => 'new_name',
            ]);

            //request
            $this->expectException(UnauthorizedException::class);
            $this->expectExceptionMessage('Password has been changed, please login again');

            $request = $this->requestWithToken($token);

            $middleware = new \App\Http\Middleware\ApiAuthenticate();

            $middleware->handle($request, function () {
            });
        }

Since I use request()->user() in my middleware, the request has to run through auth:sanctum first to get user model. So,how to properly test my middleware?

0 likes
1 reply

Please or to participate in this conversation.