I'm diving into testing and trying to test a registration form that includes Google reCaptcha V3. I've done a lot of searching here and on the net trying to find this solution. I've tried several that I've come across but none work. Below is the templates and code involved. Would appreciate any help.
recaptcha.blade.php
<script type="text/javascript">
$(function () {
$('.recaptcha').on('submit', function (event) {
event.preventDefault();
grecaptcha.ready(function () {
grecaptcha.execute("{{ config('services.recaptcha.site_key') }}", {action: 'submit'}).then(function (token) {
$('.recaptcha').append('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$('.recaptcha').unbind('submit').submit();
});
});
});
});
</script>
RegisterFormRequest.php
public function rules(): array
public function rules(): array
{
return [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|min:4|max:32|email|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required',
'timezone' => 'required',
'g-recaptcha-response' => app(ReCaptcha::class),
];
}
ReCaptcha.php
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$response = Http::asForm()->post(config('services.recaptcha.url'), [
'secret' => config('services.recaptcha.secret_key'),
'response' => $value,
]);
if (! ($response->json()["success"] ?? false)) {
$fail('The google recaptcha response failed.');
}
}
I'm using Pest and have this much for the test already. However, it fails due to the recaptcha.
it('can register', function () {
$response = $this->post('/register', [
'first_name' => 'Joe Dirt',
'last_name' => 'Jones',
'email' => '[email protected]',
'password' => 'somethingrandom ',
'password_confirmation' => 'somethingrandom ',
'timezone' => 'America/New_York',
'g-recaptcha-response' => '????????',
])->assertRedirect('email/verify');
$this->assertDatabaseHas('users', [
'email' => '[email protected]',
]);
$this->assertDatabaseHas('profiles', [
'first_name' => 'Joe',
'last_name' => 'Dirt',
'timezone' => 'America/New_York',
]);
});