Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel phpunit test with api token authentication

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'
            ]
        ]);
    }
like image 282
Chris Avatar asked Oct 16 '17 12:10

Chris


2 Answers

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'
        ]
    ]);
}
like image 70
Tommy Lohil Avatar answered Sep 27 '22 18:09

Tommy Lohil


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');
like image 25
Lerzenit Avatar answered Sep 27 '22 16:09

Lerzenit