automica's avatar

Mocking passport for feature test

Hi all, I'm working on a feature for an api where a user can login directly after registration.

I'm doing this by generating a token using passport:

$token = $user->createToken('token')->accessToken; and then passing it back in the response.

Whilst I've tested this against the dev db using postman (and get a token back correctly), I'm having some issues with this as part of a feature test and get the following error:

RuntimeException: Personal access client not found. Please create one. in /var/www/html/vendor/laravel/passport/src/ClientRepository.php:122

This suggests I need to install passport and I have attempted this as such:

php artisan passport:install --force --env=testing

but the command signature doesn't accept the --env flag to target the testing db.

I've tried partial mocking the createToken method on User but it doesnt look like its being called as I would expect so I'm at a bit of a loss.

Any work arounds / help with mocking would be appreciated.

0 likes
3 replies
martinbean's avatar

@automica Why are you manually creating tokens? Passport is meant for adding an OAuth server to your application, so you should be using one of the standard OAuth flows to authenticate users.

automica's avatar

@martinbean TBH I don't know why its been implemented this way (nor do I have any influence in being able to change this).

Any advice on how to resolve my immediate issue with being able to test this?

BTW in here: https://www.toptal.com/laravel/passport-tutorial-auth-user-access

public function register (Request $request) {
    $validator = Validator::make($request->all(), [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6|confirmed',
    ]);
    if ($validator->fails())
    {
        return response(['errors'=>$validator->errors()->all()], 422);
    }
    $request['password']=Hash::make($request['password']);
    $request['remember_token'] = Str::random(10);
    $user = User::create($request->toArray());
    $token = $user->createToken('Laravel Password Grant Client')->accessToken;
    $response = ['token' => $token];
    return response($response, 200);
}

the tutorial suggests something similar to what I'm doing. Is that incorrect too?

automica's avatar
automica
OP
Best Answer
Level 54

the solution I've found is to add

    $this->artisan('passport:install');

to setUp() in TestCase.php

Please or to participate in this conversation.