smarber smarber - 1 month ago 12
PHP Question

submit a form using ajax in functional test

I'm creating a functional test for the inscription part of my project and I need to know how to test it if the form needs to go in an ajax request, otherwise the server will always return an empty inscription form.

Looks like the submit method doesn't take an argument that specifies whether it's an ajax a request unlike request method -> http://api.symfony.com/2.3/Symfony/Component/HttpKernel/Client.html#method_submit

Thanks

UPDATE1

////////////////////////////////////////////////
// My functional test looks exactly like this //
////////////////////////////////////////////////
$form = $buttonCrawlerNode->form(array(
'name' => 'Fabien',
'my_form[subject]' => 'Symfony rocks!',
));
// There is no way here I can tell client to submit using ajax!!!!
$client->submit($form);

// Why can't we tell client to submit using ajax???
// Like we do here in the request m├ęthod
$client->request(
'GET',
'/post/hello-world',
array(),
array(),
array('HTTP_X-Requested-With' => 'XMLHttpRequest')
);

Answer

The Symfony Request Object intercept an XmlHttpRequest in the header of the request. So simply add the correct header to your request in the test class, as example:

class FooFunctionalTest extends WebTestCase
{
    $client = static::CreateClient();
    $url = '/post/hello-world';
    // makes the POST request
    $crawler = $client->request('POST', $url, array(
        'my_form' => array(
            'subject' => 'Symfony rocks!'
        )),
        array(),
        array(
            'HTTP_X-Requested-With' => 'XMLHttpRequest',
        )
    );
}

Hope this help

Comments