Symfony how to validate an AJAX request

In my project, I have a part of my form that submits an AJAX request:

 $.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 would like to be able to test this request in isolation, but I'm not sure how to write the request object.

So far, my first try:

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

      

Failed because it seems to be submitting the form (I get an error related to the form field, completely unrelated to a missing AJAX request).

Can anyone demonstrate how to write such a test correctly?

+3


source to share


2 answers


Does this URL require authentication?

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



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

      

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

+3


source


The exact syntax I used to solve this problem was as follows:

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 don't need: 'HTTP_X-Requested-With' => 'XMLHttpRequest'

in the last argument of the array.

Also, I had the array('sample_number' => 67655)

wrong argument.

+1


source







All Articles