I am trying to test a route that does something different in the controller whether or not the request is ajax or not.
public function someAction(Request $request)
{
if($request->ajax()){
// do something for ajax request
return response()->json(['message'=>'Request is ajax']);
}else{
// do something else for normal requests
return response()->json(['message'=>'Not ajax']);
}
}
My test:
public function testAjaxRoute()
{
$url = '/the-route-to-controller-action';
$response = $this->json('GET', $url);
dd($response->dump());
}
When I run the test and just dump the response I get back 'Not ajax' - which makes sense I guess cause $this->json() is just expecting back a json response, not necessarily making an ajax request. But how can I correctly test this? I have been commenting the...
// if($request->ajax(){
...need to test this code
// }else{
// ...
// }
every time I need to run the test on that portion of code. I'm looking for how to make an ajax request in my test case I guess...
In Laravel 5.4 tests this->post() and this->get() methods accept headers as the third parameter. Set HTTP_X-Requested-With to XMLHttpRequest
$this->post($url, $data, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
I added two methods to tests/TestCase.php to make easier.
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Make ajax POST request
*/
protected function ajaxPost($uri, array $data = [])
{
return $this->post($uri, $data, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
}
/**
* Make ajax GET request
*/
protected function ajaxGet($uri, array $data = [])
{
return $this->get($uri, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
}
}
Then from within any test, let's say tests/Feature/HomePageTest.php, I can just do:
public function testAjaxRoute()
{
$url = '/ajax-route';
$response = $this->ajaxGet($url)
->assertSuccessful()
->assertJson([
'error' => FALSE,
'message' => 'Some data'
]);
}
Try $response = \Request::create($url, 'GET', ["X-Requested-With" => "XMLHttpRequest"])->json();