I'm testing api endpoint which is authenticated with laravel passport. I'm writing a feature test for checking if oauth/token
can return a valid access_token. It is working fine in postman but I am using a different database for testing so when I run the test I'm always getting 400 error. Though I'm able to test all authenticated routes but I'm stuck when I want to test api/login
or oauth/token
endpoints. I'm running artisan command to install passport for test database. How to get client id and secret?
In TestCase class
public function setUp(): void
{
parent::setUp();
Artisan::call('migrate', ['-vvv' => true]);
Artisan::call('passport:install', ['-vvv' => true]);
Artisan::call('db:seed', ['-vvv' => true]);
}
LoginTest class
public function test_it_returns_a_valid_token_if_credentials_do_match()
{
$client = Passport::client();
$user = User::factory()->create([
'email' => $email = '[email protected]',
'password' => $password = '12345678'
]);
$body = [
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $email,
'password' => $password
];
$this->json('POST', '/oauth/token', $body)
->assertStatus(200);
}
Here $client = Passport::client()
return null. I didn't find any solution to get oauth client credentials.
Actually $client = Passport::client();
doesn't return client.
I have found a solution to create client from LoginTest.
$user = User::factory()->create([
'email' => $email = '[email protected]',
'password' => $password = '12345678'
]);
$client = ClientFactory::new()->asPasswordClient()->create(['user_id' => $user->id]);
$response = $this->json(
'POST', '/oauth/token',
[
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $user->email,
'password' => $password,
]
)
->assertStatus(200);