How to simulate xmlHttpRequests in a laravel testcase?

You need to prefix the actual header with HTTP_, no need to use HTTP_CUSTOM:

$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$this->call('get', '/ajax-route', array(), array(), $server);

Alternative syntax which looks a bit better IMO:

$this->client->setServerParameter('HTTP_X-Requested-With', 'XMLHttpRequest');
$this->call('get', '/ajax-route');

Here are some similar code examples for JSON headers (Request::isJson() and Request::wantsJson()):

$this->client->setServerParameter('HTTP_CONTENT_TYPE', 'application/json');
$this->call('get', '/is-json');

$this->client->setServerParameter('HTTP_ACCEPT', 'application/json');
$this->call('get', '/wants-json');

Here's a useful helper method you can put in your TestCase:

protected function prepareAjaxJsonRequest()
{
    $this->client->setServerParameter('HTTP_X-Requested-With', 'XMLHttpRequest');
    $this->client->setServerParameter('HTTP_CONTENT_TYPE', 'application/json');
    $this->client->setServerParameter('HTTP_ACCEPT', 'application/json');
}

Here's the solution for Laravel 5.2.

$this->json('get', '/users/2/routes');

It's that simple.


Intenally, json method applies following headers:

'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
'CONTENT_TYPE'   => 'application/json',
'Accept'         => 'application/json',

In Laravel 5:

$this->get('/users/2/routes', ['HTTP_X-Requested-With' => 'XMLHttpRequest']);

Then you can chain the normal assertions:

$this->get('/users/2/routes', ['HTTP_X-Requested-With' => 'XMLHttpRequest'])
    ->seeJsonStructure([
        '*' => ['id', 'name'],
    ]);