Laravel 5.4 testing route protected by $request->ajax(), how to make test ajax request? Laravel 5.4 testing route protected by $request->ajax(), how to make test ajax request? ajax ajax

Laravel 5.4 testing route protected by $request->ajax(), how to make test ajax request?


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.

<?phpnamespace 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();