【问题标题】:Laravel 5.4 testing route protected by $request->ajax(), how to make test ajax request?Laravel 5.4 测试路由受 $request->ajax() 保护,如何发出测试 ajax 请求?
【发布时间】:2017-09-13 09:24:55
【问题描述】:

我正在尝试测试在控制器中执行不同操作的路由,无论请求是否为 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']);
    }
}

我的测试:

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

当我运行测试并转储响应时,我得到了“非 ajax”——我猜这是有道理的,因为 $this->json() 只是期待得到一个 json 响应,而不是必须发出ajax请求。但是我怎样才能正确地测试呢?我一直在评论...

// if($request->ajax(){
    ...need to test this code
// }else{
    // ...
// }

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

【问题讨论】:

    标签: php ajax laravel-5


    【解决方案1】:

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

    $this->post($url, $data, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
    

    我在 tests/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'));
        }
    }
    

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

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

    【讨论】:

      【解决方案2】:

      试试$response = \Request::create($url, 'GET', ["X-Requested-With" =&gt; "XMLHttpRequest"])-&gt;json();

      【讨论】:

      • 这会发出一个请求,但它没有其他测试功能,例如 ->assertStatus(200) 和 ->decodeResponseJson()
      • 显示第三个参数是 ["X-Requested-With" => "XMLHttpRequest"] 对您很有帮助,其中 $this->get() 和 $this->post() 也除外并且它们从构成所有 laravel 测试内容的任何类扩展......所以,谢谢!!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多