game-village-politics-backend/tests/Feature/AuthTest.php

43 lines
2.3 KiB
PHP
Raw Normal View History

<?php
use App\Models\User;
it('registers a player and returns a bearer token', function () {
$response = $this->postJson('/api/auth/register', [
'name' => 'Ada', 'email' => 'Ada@Example.test', 'password' => 'secret-pass', 'terms' => true,
]);
$response->assertOk()->assertJsonPath('user.name', 'Ada')->assertJsonStructure(['token', 'user' => ['id', 'name', 'email']]);
$user = User::where('email', 'ada@example.test')->first();
expect($user->tokens)->toHaveCount(1)->and($user->terms_accepted_at)->not->toBeNull();
});
it('refuses a second account with the same email', function () {
User::factory()->create(['email' => 'ada@example.test']);
$this->postJson('/api/auth/register', ['name' => 'Ada', 'email' => 'ada@example.test', 'password' => 'secret-pass', 'terms' => true])
->assertStatus(422)->assertJsonPath('code', 'email_taken')->assertJsonPath('field', 'email');
});
it('logs in with the right password only', function () {
User::factory()->create(['email' => 'ada@example.test', 'password' => 'secret-pass']);
$this->postJson('/api/auth/login', ['email' => 'ada@example.test', 'password' => 'wrong-pass'])
->assertStatus(422)->assertJsonPath('code', 'invalid_credentials');
$this->postJson('/api/auth/login', ['email' => 'ada@example.test', 'password' => 'secret-pass'])
->assertOk()->assertJsonStructure(['token']);
});
it('checks every field and names the one that is wrong', function () {
User::factory()->create(['name' => 'Taken One']);
$try = fn (array $over) => $this->postJson('/api/auth/register', [...['name' => 'Ada', 'email' => 'ada@example.test', 'password' => 'secret-pass', 'terms' => true], ...$over]);
$try(['name' => 'A'])->assertStatus(422)->assertJsonPath('code', 'name_invalid')->assertJsonPath('field', 'name');
$try(['name' => '<script>'])->assertJsonPath('code', 'name_invalid');
$try(['name' => 'taken one'])->assertJsonPath('code', 'name_taken');
$try(['email' => 'not-an-email'])->assertJsonPath('code', 'email_invalid');
$try(['password' => 'short'])->assertJsonPath('code', 'password_short');
$try(['terms' => false])->assertJsonPath('code', 'terms_required')->assertJsonPath('field', 'terms');
$try(['name' => ' Ada Lovelace '])->assertOk()->assertJsonPath('user.name', 'Ada Lovelace');
});