Skip to content

Commit

Permalink
Add test coverage for XMLHttpRequest behaviour and ensure its run
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanmitchell committed Jul 1, 2024
1 parent 085847d commit 4fe64f5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
8 changes: 4 additions & 4 deletions src/Http/Controllers/FormController.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,6 @@ private function formFailure($params, $errors, $form)
{
$request = request();

if ($request->isPrecognitive() || $request->wantsJson()) {
throw ValidationException::withMessages($errors);
}

if ($request->ajax()) {
return response([
'errors' => (new MessageBag($errors))->all(),
Expand All @@ -122,6 +118,10 @@ private function formFailure($params, $errors, $form)
], 400);
}

if ($request->isPrecognitive() || $request->wantsJson()) {
throw ValidationException::withMessages($errors);
}

$redirect = Arr::get($params, '_error_redirect');

$response = $redirect ? redirect($redirect) : back();
Expand Down
30 changes: 25 additions & 5 deletions tests/Tags/Form/FormCreateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -934,12 +934,8 @@ public function it_removes_any_uploaded_assets_when_a_listener_throws_a_validati
}

#[Test]
public function it_renders_exceptions_thrown_during_precognitive_requests_as_standard_laravel_errors()
public function it_renders_exceptions_thrown_during_json_requests_as_standard_laravel_errors()
{
if (! method_exists($this, 'withPrecognition')) {
$this->markTestSkipped();
}

Event::listen(function (\Statamic\Events\FormSubmitted $event) {
throw ValidationException::withMessages(['some' => 'error']);
});
Expand All @@ -957,4 +953,28 @@ public function it_renders_exceptions_thrown_during_precognitive_requests_as_sta
$this->assertArrayHasKey('errors', $json);
$this->assertSame($json['errors'], ['some' => ['error']]);
}

#[Test]
public function it_renders_exceptions_thrown_during_xml_http_requests_in_statamic_error_format()
{
Event::listen(function (\Statamic\Events\FormSubmitted $event) {
throw ValidationException::withMessages(['some' => 'error']);
});

$response = $this
->withHeaders([
'X-Requested-With' => 'XMLHttpRequest',
])
->postJson('/!/forms/contact', [
'name' => 'Name',
'email' => '[email protected]',
'message' => 'This is a message',
]);

$json = $response->json();

$this->assertArrayHasKey('error', $json);
$this->assertArrayHasKey('errors', $json);
$this->assertSame($json['error'], ['some' => 'error']);
}
}

0 comments on commit 4fe64f5

Please sign in to comment.