How to test authentication via API with Laravel Passport?

前端 未结 7 1112
轮回少年
轮回少年 2020-12-24 07:55

I\'m trying to test the authentication with Laravel\'s Passport and there\'s no way... always received a 401 of that client is invalid, I\'ll leave you what I\'ve tried:

7条回答
  •  盖世英雄少女心
    2020-12-24 08:25

    Optimise for unnecessary DB migrations

    Here is an example that ensures that you are still able to write tests that do not depend on the database - not running db migrations.

    namespace Tests;
    
    use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
    use Illuminate\Support\Facades\Schema;
    use Laravel\Passport\ClientRepository;
    
    abstract class TestCase extends BaseTestCase
    {
        use CreatesApplication;
    
        public function setUp(): void
        {
            parent::setUp();
    
            if (Schema::hasTable('oauth_clients')) {
                resolve(ClientRepository::class)->createPersonalAccessClient(
                    null, config('app.name') . ' Personal Access Client', config('app.url')
                );
            }
        }
    }
    

    Then in your test:

    ...
    
    use RefreshDatabase;
    
    /**
     * Test login
     *
     * @return void
     */
    public function test_login()
    {
        $this->withExceptionHandling();
        $user = factory(User::class)->create([
            'password' => 'secret'
        ]);
    
        $response = $this->json('POST', route('api.auth.login'), [
            'email' => $user->email,
            'password' => 'secret',
        ]);
    
        $response->assertStatus(200);
        $response->assertJsonStructure([ 
           //...
        ]);
    }
    
    ...
    

    This way you are able to write tests that do not have any db migrations

提交回复
热议问题