I have a test which is trying to login and get details. I need to pass a bearer token in request header for this operation. Please see the below code. I could see that the header seldom has the headers that I set. Can anyone give me a pointer to fix this issue?
I am using Laravel 7.2.2, PHP 7.4,
And I am running php artisan test
Code:
public function a_user_can_get_details()
{
$this->create_user();
$response = $this->json('POST',
'/api/login',
[
"email" => "john.doe@example.com",
"password" => "john123"
]);
$response->assertSuccessful();
$token = Str::replaceLast('"', '', Str::replaceFirst('"', '', $response->getContent()));
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $token
];
$response = $this->withHeaders($headers)
->get('api/user');
$response->assertSuccessful();
$this->assertCount(1, User::all());
}
And here is the error I am getting. Actually, the test must pass. That is the right user name and password:
Response status code [403] is not a successful status code. Failed asserting that false is true.
at tests/Feature/UserTest.php:141
137|
138| $response = $this->withHeaders($headers)
139| ->get('api/user');
140|
> 141| $response->assertSuccessful();
142| $this->assertCount(1, User::all());
143|
144| }
145|
Written with StackEdit.
Top comments (1)
Thank you for the response. You were right for one part. I believe the string manipulation made is issue there. Yet, the issue still exists. I got 401 now.
I changed my header array like this:
I tried die and dump the $response, and here is the header array from the dd: