Symfony如何测试AJAX请求

时间:2022-10-24 13:52:25

In my project I have a piece of my form that sends an AJAX request:

在我的项目中,我有一段发送AJAX请求的表单:

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

Which activates the following controller method:

这会激活以下控制器方法:

/**
 * @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);
}

I'd like to be able to test this request in isolation, but I'm unsure how to write the request object.

我希望能够单独测试这个请求,但我不确定如何编写请求对象。

So far my first attempt:

到目前为止我第一次尝试:

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);
    }

Fails because it appears to be submitting the form (I get an error related to a form field completely unrelated to the AJAX request being blank).

失败,因为它似乎是提交表单(我得到一个与AJAX请求完全无关的表单字段相关的错误是空白的)。

Can anyone demonstrate how to correctly write such a test?

任何人都可以演示如何正确编写这样的测试吗?

2 个解决方案

#1


3  

Does this URL need authentication?

此URL是否需要身份验证?

I like to use LiipFunctionalTestBundle for my functional tests and they usually looks like this:

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

Maybe the error you are getting is the login form asking for authentication?

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

#2


1  

The exact syntax I used to solve this problem was:

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

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);
    }

I believe I didn't need: 'HTTP_X-Requested-With' => 'XMLHttpRequest' in the final array argument.

我相信我不需要:'HTTP_X-Requested-With'=>'XMLHttpRequest'在最终的数组参数中。

Additionally, I had array('sample_number' => 67655) in the wrong argument.

另外,我在错误的参数中有数组('sample_number'=> 67655)。

#1


3  

Does this URL need authentication?

此URL是否需要身份验证?

I like to use LiipFunctionalTestBundle for my functional tests and they usually looks like this:

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

Maybe the error you are getting is the login form asking for authentication?

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

#2


1  

The exact syntax I used to solve this problem was:

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

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);
    }

I believe I didn't need: 'HTTP_X-Requested-With' => 'XMLHttpRequest' in the final array argument.

我相信我不需要:'HTTP_X-Requested-With'=>'XMLHttpRequest'在最终的数组参数中。

Additionally, I had array('sample_number' => 67655) in the wrong argument.

另外,我在错误的参数中有数组('sample_number'=> 67655)。