2017-04-25 21 views
3

在項目中,我有我的一塊形式發送一個AJAX請求:的Symfony如何測試一個AJAX請求

$.ajax({ 
    url: '/bio_control/sample', 
    type: 'POST', 
    dataType: 'json', 
    data: {sample_number: $(input_field).val()}, 
}); 

激活以下控制器方法:

/** 
* @Route("/bio_control/sample", name="get_bio_control_sample") 
*/ 
public function getBioControlSampleAction(Request $request) 
{ 

    $sample_number = $request->request->get('sample_number'); 

    /** 
    * Additional logic not shown for brevity. 
    */ 

    $user_id = $user->getId(); 
    $response = array("code" => 100, "success" => true, "sample_number" => $sample_number, "sample_data" => $sample[0], "new_user" => false, "user_id" => $user_id); 

    return new JsonResponse($response); 
} 

我會喜歡能夠單獨測試這個請求,但我不確定如何編寫請求對象。

到目前爲止,我的第一次嘗試:

public function testGetBioControlSample() 
    { 
     $helper = $this->helper; 
     $client = $this->makeClient(); 
     $crawler = $client->request('POST', "/bio_control/sample", array(), array('sample_number' => 67655), array(
      'CONTENT_TYPE' => 'application/json', 
      'HTTP_X-Requested-With' => 'XMLHttpRequest' 
     )); 
     $this->assertStatusCode(200, $client); 
    } 

失敗,因爲它似乎是提交表單(我得到相關的表單字段完全無關的AJAX請求是空白的錯誤)。

任何人都可以演示如何正確編寫這樣的測試?

回答

3

此URL是否需要驗證?

我喜歡用LiipFunctionalTestBundle我的功能測試,他們通常是這樣的:

<?php 

declare(strict_types=1); 

namespace Tests\Your\Namespace; 

use Liip\FunctionalTestBundle\Test\WebTestCase; 

class PostResourceActionTest extends WebTestCase 
{ 
    public function testShouldReturnResponseWithOkStatusCode(): void 
    { 
     $credentials = [ 
      'username' => 'user', 
      'password' => 'pass' 
     ]; 
     $client = $this->makeClient($credentials); 

     $payload = ['foo' => 'bar']; 
     $client->request(
      'POST', 
      '/the/url/', 
      $payload, 
      [], 
      ['HTTP_Content-Type' => 'application/json'] 
     ); 

     $this->assertStatusCode(200, $client); 
    } 
} 

也許你所得到的錯誤是登錄表單要求身份驗證?

+0

我使用相同的包,並且在使用相同流程的所有其他測試中都進行了身份驗證。但是,我嘗試了你的語法,它完美的工作 - 所以謝謝! – Darkstarone

+1

不客氣。 –

1

我用來解決這個問題的確切語法是:

public function testGetBioControlSample() 
    { 
     $helper = $this->helper; 
     $client = $this->makeClient(); 

     $crawler = $client->request(
      'POST', 
      "/bio_control/sample", 
      array('sample_number' => 67655), 
      array(), 
      array('HTTP_Content-Type' => 'application/json') 
     ); 

     $JSON_response = json_decode($client->getResponse()->getContent(), true); 

     $this->assertStatusCode(200, $client); 
     $this->assertNotEmpty($JSON_response); 

     $this->assertEquals($JSON_response["code"], 100); 
     $this->assertEquals($JSON_response["success"], true); 
     $this->assertEquals($JSON_response["sample_number"], 67655); 
    } 

我相信我並不需要:在最後的數組參數'HTTP_X-Requested-With' => 'XMLHttpRequest'

此外,我有array('sample_number' => 67655)在錯誤的參數。

+1

此前,您還錯誤地將有效負載作爲'$ client-> request()'方法的第四個參數發送,也就是'$ files'。 –

+0

啊,你是對的,再次感謝! – Darkstarone