Skip to content

Test API whith authenticate user when using Laravel Passport?

I am using Passport for user authentication and I want to test the API with PHPUnit in Laravel. How can we have authenticated user?

Laravel Passport made it easy:

Passport::actingAs(
    $user, // user instance
    ['create-servers'] // scopes that should be granted
);

Example of how to test API in Laravel with Passport:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Laravel\Passport\Passport;

class ArticleTest extends TestCase
{
    public function test_article_creation() {

        // actingAs() function generates token needed for authunticate user
        // we use factory() to create user, instead you can set user manually
        $this->user = Passport::actingAs(
            factory(User::class)->create()
        );

        $payload = [
            "title" => 'Example title',
            "body" => 'Example long content',
        ];

        // send post request to api with json body (payload)
        $response = $this->json('POST', '/api/article', $payload);

        // assert the status code of response is 201 that means resource "created"
        // you can check status 200 for example
        $response->assertStatus(201);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *