Files
ppeasy_vg12/tests/Unit/Http/Resources/UserResourceTest.php
T
2026-10-09 08:21:06 +02:00

74 lines
1.9 KiB
PHP

<?php
use App\Http\Resources\UserResource;
use App\Models\Role;
use App\Models\User;
use Facades\Tests\Setup\UserFactory;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->artisan('db:seed');
});
test('resource has expected keys', function () {
$user = User::factory()->create();
$array = (new UserResource($user))->toArray(fakeRequest($user));
$expected = [
'id', 'first_name', 'last_name', 'username', 'email', 'phone', 'avatar',
'address', 'country_id', 'role_id', 'status', 'birthday', 'last_login',
'two_factor_country_code', 'two_factor_phone', 'two_factor_options',
'email_verified_at', 'created_at', 'updated_at', 'country',
];
foreach ($expected as $key) {
$this->assertArrayHasKey($key, $array, "missing key: $key");
}
});
test('role is hidden without permission', function () {
$role = Role::factory()->create();
$user = User::factory()->create(['role_id' => $role->id]);
$user->load('role');
$serialized = serializeResource($user);
$this->assertArrayNotHasKey('role', $serialized);
});
test('role is visible with permission', function () {
$admin = UserFactory::withPermissions('roles.manage')->create();
$admin->load('role');
$serialized = serializeResource($admin);
$this->assertArrayHasKey('role', $serialized);
});
test('allowed includes', function () {
$this->assertSame(['role', 'country'], UserResource::allowedIncludes());
});
function fakeRequest(User $user): Request
{
$request = Request::create('/');
$request->setUserResolver(fn () => $user);
return $request;
}
/**
* Serialize the resource through JSON to filter out MissingValue placeholders.
*/
function serializeResource(User $user): array
{
return json_decode(
(new UserResource($user))->toResponse(fakeRequest($user))->getContent(),
true,
)['data'];
}