I am using Laravel Passport and have a logout function in the controller. See below:
public function logout(Request $request){
auth()->user()->token()->revoke();
$response = ['message' => 'You have been successfully logged out!'];
return response($response, 200);
}
I am now trying to write a unit test for this but the user stays logged in even after the logout and the token being revoked. I have found this Method Illuminate\Auth\RequestGuard::logout does not exist Laravel Passport but even this solution does not work for me. I am guessing it might be because I am using Laravel 8. My Unit test looks like this:
public function testLogout()
{
//Random email and password
$email = $this->faker->email;
$password = $this->faker->password(8);
//Create a user
$this->createUser($this->faker->name, $email, $password);
//Data for the post request
$data = [
'email' => $email,
'password' => $password
];
//Try login
$response = $this->json('POST','api/login', $data);
//Assert it was successful
$response->assertStatus(200);
//Assert we received a token
$this->assertArrayHasKey('token', $response->json());
//Get the token
$token = $response->json()['token'];
//Setup authenticated header
$header = [
'Authorization' => 'Bearer '.$token
];
//try to access authenticated route
$response = $this->json('get', 'api/ads', [], $header);
//Assert it was successful
$response->assertStatus(200);
$this->resetAuth();
//Logout the user
$response = $this->post('api/logout', [], $header);
//Assert it was successful
$response->assertStatus(200);
//try to access authenticated route
$response = $this->json('get', 'api/ads', [], $header);
//Assert it returns unathorized error
$response->assertStatus(401);
//Delete the user
User::where('email', $email)->delete();
}
And the result is the following:
Expected status code 401 but received 200. Failed asserting that 401 is identical to 200.