sintonia_webapp/tests/Feature/Auth/RegistrationTest.php

96 lines
3.3 KiB
PHP

<?php
use App\Models\User;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use function Pest\Laravel\postJson;
it('should return unauthenticated error', function () {
$response = postJson(route('/register'), [
'username' => 'unauthenticatedError',
'password' => 'password',
'password_confirmation' => 'password',
'email' => 'unauthenticatedError@unauthenticatedError.test',
'type' => 'dj',
]);
$response->assertStatus(401)
->assertJsonValidationErrors(['username' => 'The username field is required.']);
});
it('should return an error if username is missing', function () {
$response = postJson(route('register'), [
'password' => 'password',
'password_confirmation' => 'password',
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['username' => 'The username field is required.']);
});
it('should return an error if password is missing', function () {
$response = postJson(route('register'), [
'username' => 'testuser',
'password_confirmation' => 'password',
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['password' => 'The password field is required.']);
});
it('should return an error if password confirmation is missing', function () {
$response = postJson(route('register'), [
'username' => 'testuser',
'password' => 'password',
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['password_confirmation' => 'The password confirmation field is required.']);
});
it('should create a new user successfully', function () {
// Mock the CreatesNewUsers implementation
$creatorMock = Mockery::mock(CreatesNewUsers::class);
$creatorMock->shouldReceive('create')
->once()
->with([
'username' => 'testuser',
'password' => 'password',
'password_confirmation' => 'password'
])
->andReturn(new User(['username' => 'testuser'])); // Adjust based on your actual User model
$this->app->instance(CreatesNewUsers::class, $creatorMock);
$response = postJson(route('register'), [
'username' => 'testuser',
'password' => 'password',
'password_confirmation' => 'password'
]);
$response->assertStatus(201)
->assertJson(['message' => 'User created successfully', 'user' => ['username' => 'testuser']]);
// Assert that the user was actually created in the database
$this->assertDatabaseHas('cc_subjs', ['username' => 'testuser']);
});
it('should handle exceptions during user creation', function () {
// Mock the CreatesNewUsers implementation to throw an exception
$creatorMock = Mockery::mock(CreatesNewUsers::class);
$creatorMock->shouldReceive('create')
->once()
->withAnyArgs()
->andThrow(new Exception('Failed to create user'));
$this->app->instance(CreatesNewUsers::class, $creatorMock);
$response = postJson(route('register'), [
'username' => 'testuser',
'password' => 'password',
'password_confirmation' => 'password'
]);
$response->assertStatus(422)
->assertJson(['errors' => 'Failed to create user']);
});