Reputation: 53
So i'm trying to create an auth repository test using phpunit but i keep getting the error 'Call to a member function createToken() on null'. I think this is due to the RefreshDatabase trait but i'm installing passport on setup so i'm a bit lost. Any help is appreciated!
AuthRepository test
namespace Tests\Repository;
use App\Contracts\Auth;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class AuthRepositoryTest extends TestCase
{
use RefreshDatabase;
protected $authRepository;
protected function setUp(): void
{
parent::setUp();
$this->artisan('passport:install');
$this->authRepository = app()->make(Auth::class);
}
/**
* Test Successful Login
*
* @return void
*/
public function testSuccessfulLogin(): void
{
$request = new \Illuminate\Http\Request();
$request->setMethod('POST');
$request->replace(['name' => 'test', 'email' => 'test', 'password' => 'testing']);
$this->authRepository->register($request);
$request = new \Illuminate\Http\Request();
$request->setMethod('POST');
$request->replace(['email' => 'test', 'password' => 'testing']);
$this->authRepository->login($request);
}
}
Test Case
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function setUp(): void
{
parent::setup();
}
}
AuthRepository
<?php
namespace App\Repositories;
use App\Contracts\Auth;
use Illuminate\Support\Facades\Auth as Authenticate;
use App\User;
class AuthRepository implements Auth
{
public function Register($request)
{
$user = new User([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password'))
]);
$user->save();
return $user;
}
public function Login($request)
{
$credentials = $request->all();
if (!Authenticate::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
$token->save();
return $tokenResult;
}
}
Upvotes: 0
Views: 4014
Reputation: 2248
This is happened because the controller is trying to get the user data and create a token based on that.
In your case (happened to me too), there was a user variable which pointing the request to get the user credential while the user data is unknown because the user is not yet logged in.
To be clear, please take a look at your code within this line:
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
To fix that, change the line of $user = $request->user()
to this:
$user = User::whereEmail($request->email)->first();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
Upvotes: 1