So all I am trying to do is test my API login endpoint to test that the process of validation actually works. As usual, in the implementation, I deliberately pass in wrong values or empty values and then test to see if the errors are thrown. Below is my current implementation:
Test Class/Method:
public function test_user_can_not_sign_up_on_validation_error()
{
$this->withoutExceptionHandling();
$user = [
'firstname' => 'Dela',
'lastname' => 'Akakpo',
'date_of_birth' => '1996-01-01',
'gender' => 'Male',
'phone_number' => '0209059199',
'address' => 'Madina Accra',
'email' => '',
'password' => 'password',
'country_id' => Country::factory()->create()->id
];
$response = $this->postJson(route('api.register'), $user);
$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
$response->assertJsonValidationErrors('email');
}
As seen above, the email field is empty and hence I am testing to see if the validation error has the email value in it using the assertJsonValidationErrors method.
Unfortunately, this does not work. It throws the Illuminate\Validation\ValidationException.
Stack trace below:
FAIL Tests\Feature\Auth\RegistrationTest
⨯ user can not sign up on validation error
---
• Tests\Feature\Auth\RegistrationTest > user can not sign up on validation error
Illuminate\Validation\ValidationException
The given data was invalid.
at vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php:138
134▕ * @throws \Illuminate\Validation\ValidationException
135▕ */
136▕ protected function failedValidation(Validator $validator)
137▕ {
➜ 138▕ throw (new ValidationException($validator))
139▕ ->errorBag($this->errorBag)
140▕ ->redirectTo($this->getRedirectUrl());
141▕ }
142▕
+17 vendor frames
18 app/Http/Middleware/LogRequests.php:20
Illuminate\Pipeline\Pipeline::Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
+31 vendor frames
50 tests/Feature/Auth/RegistrationTest.php:70
Illuminate\Foundation\Testing\TestCase::postJson("https://afap-ims.test/api/v1/register")
Tests: 1 failed
Time: 0.38s