How can I add the authorization header in phpunit? I am testing a json api that requires an api_token. laravel docs provide a actingAs method. But this does not work in my case because the api token is not directly related to the users table.
EDIT:
public function test_returns_response_with_valid_request()
{
$response = $this->json('post', '/api/lookup', [
'email' => '[email protected]'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
You can use withHeader method and pass in your token, and this works on my local (Laravel 6)
public function test_returns_response_with_valid_request()
{
// define your $token here
$response = $this->withHeader('Authorization', 'Bearer ' . $token)
->json('post', '/api/lookup', [
'email' => '[email protected]'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
Or you can use actingAs with look at docs here with api guard
public function test_returns_response_with_valid_request()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user, 'api')
->json('post', '/api/lookup', [
'email' => '[email protected]'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
According to documentation.
You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the
actingAs
method:$this->actingAs($user, 'api');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With