shopit-back/tests/Feature/Auth/LoginControllerTest.php

88 lines
2.8 KiB
PHP

<?php
namespace Tests\Feature\Auth;
use App\Domains\Auth\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class LoginControllerTest extends TestCase
{
use RefreshDatabase;
public function test_it_logs_in_a_user_and_returns_a_bearer_token(): void
{
$user = User::query()->create([
'nombre_apellido' => 'Grace Hopper',
'email' => 'grace@example.com',
'password' => Hash::make('secret123'),
]);
$response = $this->postJson('/api/login', [
'email' => 'grace@example.com',
'password' => 'secret123',
]);
$response
->assertOk()
->assertJsonPath('message', 'Sesion iniciada correctamente.')
->assertJsonPath('token_type', 'Bearer')
->assertJsonPath('user.id', $user->id)
->assertJsonPath('user.nombre_apellido', 'Grace Hopper')
->assertJsonPath('user.email', 'grace@example.com');
$this->assertIsString($response->json('token'));
$this->assertNotEmpty($response->json('token'));
$this->withHeader('Authorization', 'Bearer '.$response->json('token'))
->getJson('/api/user')
->assertOk()
->assertJsonPath('id', $user->id)
->assertJsonPath('email', 'grace@example.com');
}
public function test_it_rejects_access_to_the_current_user_endpoint_without_a_token(): void
{
$this->getJson('/api/user')->assertUnauthorized();
}
public function test_it_logs_out_the_current_token(): void
{
$user = User::factory()->create();
$token = $user->createToken('api-token')->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/logout')
->assertOk()
->assertJsonPath('message', 'Sesion cerrada correctamente.');
$this->assertDatabaseCount('personal_access_tokens', 0);
}
public function test_it_returns_a_validation_error_for_invalid_credentials(): void
{
User::query()->create([
'nombre_apellido' => 'Grace Hopper',
'email' => 'grace@example.com',
'password' => Hash::make('secret123'),
]);
$this->postJson('/api/login', [
'email' => 'grace@example.com',
'password' => 'wrong-password',
])->assertUnprocessable()->assertJsonValidationErrors(['email']);
}
public function test_it_validates_required_login_fields(): void
{
$this->postJson('/api/login', [
'email' => 'invalid-email',
'password' => '',
])->assertUnprocessable()->assertJsonValidationErrors([
'email',
'password',
]);
}
}