AJAX requests are a core part of modern Symfony applications, powering dynamic interfaces, form submissions, and background data updates without full page reloads. Symfony BrowserKit component provides the helper methods for simulating AJAX requests in functional tests. This tutorial demonstrates how to test AJAX request in Symfony 8 application.
Assume we have a controller endpoint whose job is to detect whether the incoming request was made via AJAX. The Request object provides a handy helper method, isXmlHttpRequest, which checks if the X-Requested-With header contains the XMLHttpRequest value. Below is a minimal controller that returns 1 when the request is an AJAX call and 0 otherwise.
src/Controller/AjaxController.php
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class AjaxController
{
#[Route('/ajax/check')]
public function check(Request $request): Response
{
return new Response((string) $request->isXmlHttpRequest());
}
}
Symfony functional tests are powered by the BrowserKit client, which mimics a real browser. To simplify AJAX testing, the client exposes the xmlHttpRequest method. This method behaves just like request, but it automatically sets the X-Requested-With header to XMLHttpRequest, saving us from configuring headers manually.
tests/Controller/TestAjaxController.php
<?php
namespace App\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class TestAjaxController extends WebTestCase
{
public function testCheck(): void
{
$client = static::createClient();
$crawler = $client->xmlHttpRequest('GET', '/ajax/check');
self::assertSame('1', $crawler->text());
}
}
Leave a Comment
Cancel reply