devk's avatar
Level 3

How to test Personal Access Token with Passport?

So I have this in my controller:

public function sendSimple(
    SimpleNotificationRequest $request
) {
    auth()
        ->user()
        ->notifications()
        ->forceCreate([
            'user_id' => auth()->id(),
            'oauth_auth_code_id' => auth()->user()->token()->id, // ??
            // ... other stuff
        ]);

    // other stuff

    return response()->success();
}

I would like to write a test for this. How do I create a Personal Access Token, so that the line with // ?? doesn't throw a FK reference error?

The Passport::actingAs(...) works for bypassing the auth middleware, but it doesn't actually set the token, so I run into the FK error.

What steps are required to actually create the Personal Access Token for the user, that will be found and set within the sendSimple method?

I've also tried this:

/** @test */
function it_can_successfully_trigger_a_simple_notification()
{
    Passport::actingAs(
        $user = factory(User::class)->create(),
        []
    );

    $client = app(ClientRepository::class)->createPersonalAccessClient(
        null, 'Test Personal Access Client', 'http://localhost'
    );

    \DB::table('oauth_personal_access_clients')->insert([
        'client_id' => $client->id,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $token = $user->createToken('TestToken')->accessToken;

    $res = $this
        ->withHeaders([
            'Authorization' => "Bearer $token",
        ])
        ->json(
            'POST',
            '/api/v1/notifications/simple',
            // data
        );

    dd($res->getContent());
}

But I run into the same error.

Help greatly appreciated!

0 likes
0 replies

Please or to participate in this conversation.