Search code examples
laravelauthenticationlaravel-dusk

How can write test for laravel api route with auth.basic middleware


My laravel project has an API route by auth.basic middleware which is used id of the authenticated user in the controller. when I call it in postman it works well and I get 401 when the username or password is incorrect, but in laravel APITest which extends from DuskTestCase, authentication does not take place so I get 500 instead of 401 when the user's informations were incorrect. However, by correct information, I have the same error because auth() is null.

it is written like below, which is wrong?

api.php route:

Route::get('/xxxxxx/xxxxxx/xxxxxxx', 'xxxxx@xxxx')->middleware('auth.basic');

APITest:

$response = $this->withHeaders(['Authorization' => 'Basic '. base64_encode("{$username}:{$password}")])->get("/xxxxxx/xxxxxx/xxxxxxx");

Solution

  • You can use actingAs() method for authentication in tests.

    An example from docs:

    public function testApplication()
    {
        $user = factory(App\User::class)->create();
    
        $this->actingAs($user)
             ->withSession(['foo' => 'bar'])
             ->visit('/')
             ->see('Hello, '.$user->name);
    }
    

    Another example that you can use for an API:

        $user = User::factory()->create();
    
        $response = $this->actingAs($user)->json('GET', $this->uri);
    
        $response->assertOk();
    

    For more information: https://laravel.com/docs/5.1/testing#sessions-and-authentication