Laravel 5.4测试路由受$ request-> ajax()保护,如何进行测试ajax请求?

cma*_*mac 5 php ajax laravel-5

我试图在控制器中测试一个不同的路由,无论请求是否是ajax.

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']);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试:

    public function testAjaxRoute()
{
    $url = '/the-route-to-controller-action';
    $response = $this->json('GET', $url);
    dd($response->dump());
}
Run Code Online (Sandbox Code Playgroud)

当我运行测试并且只是转储响应时,我回到'Not ajax' - 这是有道理的我猜是因为$ this-> json()只是期望回到json响应,不一定发出ajax请求.但我怎样才能正确测试呢?我一直评论......

// if($request->ajax(){
    ...need to test this code
// }else{
    // ...
// }
Run Code Online (Sandbox Code Playgroud)

每次我需要在该部分代码上运行测试.我正在寻找如何在我的测试用例中提出ajax请求...

cma*_*mac 12

在Laravel 5.4测试中,this-> post()this-> get()方法接受标头作为第三个参数.将HTTP_X-Requested-With设置XMLHttpRequest

$this->post($url, $data, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
Run Code Online (Sandbox Code Playgroud)

我添加了两个方法来测试/ TestCase.php以使其更容易.

<?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'));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在任何测试中,让我们说tests/Feature/HomePageTest.php,我可以这样做:

public function testAjaxRoute()
{
  $url = '/ajax-route';
  $response = $this->ajaxGet($url)
        ->assertSuccessful()
        ->assertJson([
            'error' => FALSE,
            'message' => 'Some data'
        ]); 
}
Run Code Online (Sandbox Code Playgroud)