symfony单元测试:添加/修改表单操作

问题描述 投票:3回答:3

我有一个没有操作的表单(使用javascript提交),并且我正在尝试为此编写单元测试,但是由于缺少“ action”属性而失败:

InvalidArgumentException:当前URI必须是绝对URL(“”)。

有一种方法可以在单元测试中添加它或使用搜寻器修改html内容?

<form id="form_search_page">
    <input type="text" name="keyword" value="" />
    <button type="submit" name="searchBtn" id="searchBtn">Search</button>
</form>


$client = $this->makeClient(true);
$url = $this->createRoute("page_index"));
$crawler = $client->request('GET', $url);
$response = $client->getResponse();

$form = $crawler->filter('#form_search_page')->form();
$params = array(
    "form[text]" => "dummy title"
);
$form->setValues($params);
$crawler = $client->submit($form);
$response = $client->getResponse();
$this->assertGreaterThan(0, $crawler->filter('.pages li')->count());
php unit-testing symfony phpunit symfony-forms
3个回答
3
投票

我找到了解决方法:

$crawler
    ->filter('form#form_search_page')
    ->reduce(function (Crawler $form) use ($router) {
        $url = $router->generate('search_page', array(), true);

        $node = $form->getNode(0);
        if (!$node->hasAttribute('action')){
            $node->setAttribute('action', $url);
            $node->setAttribute('method', 'POST');
            return true;
        }
        return false;
    })
    ->first();

2
投票

您可以像上面的示例一样测试ajax POST表单提交(假设表单带有CSRF令牌):

$crawler = $this->client->request('GET', $url);

// retrieves the form token
$token = $crawler->filter('[name="myform[_token]"]')->attr("value");

$posturl = $this->client->getContainer()->get('router')->generate("the-url-of-the-submit");
// makes the POST request
$crawler = $this->client->request('POST', $posturl, array(
    'myform' => array(
        '_token' => $token
    )),
    array(),
    array(
        'HTTP_X-Requested-With' => 'XMLHttpRequest',
    )
);

$this->assertTrue(
    $this->client->getResponse()->headers->contains(
        'Content-Type',
        'application/json'
    )
);

希望此帮助


0
投票

这是最简单的方法:

        $client = static::createClient();

        $crawler = $client->request('GET', '/contacts');

        $buttonCrawlerNode = $crawler->selectButton('submit');

        // Select the form that contains this button
        $form = $buttonCrawlerNode->form();

        // Modify the attribute action
        $form->getNode(0)->setAttribute('action', 'new-action-url');

        ...
© www.soinside.com 2019 - 2024. All rights reserved.