【问题标题】:Symfony how to test an AJAX requestSymfony 如何测试 AJAX 请求
【发布时间】:2017-09-23 00:37:10
【问题描述】:

在我的项目中,我有一个发送 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 请求完全无关的表单字段为空的错误)。

谁能演示如何正确编写这样的测试?

【问题讨论】:

    标签: ajax symfony testing phpunit symfony-3.2


    【解决方案1】:

    这个网址需要认证吗?

    我喜欢使用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);
        }
    }
    

    也许您得到的错误是登录表单要求身份验证?

    【讨论】:

    • 我正在使用相同的捆绑包,并且在使用相同流程的所有其他测试中验证良好。但是,我尝试了您的语法并且效果很好 - 非常感谢!
    【解决方案2】:

    Symfony 4.1 has a new way of testing AJAX requests:

    // Before
    $crawler = $client->request('GET', '/some/path', [], [], [
        'HTTP_X-Requested-With' => 'XMLHttpRequest',
    ]);
    
    // After
    $crawler = $client->xmlHttpRequest('GET', '/some/path');
    

    【讨论】:

      【解决方案3】:

      我用来解决这个问题的确切语法是:

      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' =&gt; 'XMLHttpRequest' 在最后的数组参数中。

      另外,我在错误的论点中有array('sample_number' =&gt; 67655)

      【讨论】:

      • 之前您错误地将有效负载作为$client-&gt;request() 方法中的第四个参数发送,它也用于$files
      猜你喜欢
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 2010-11-20
      相关资源
      最近更新 更多