Search code examples
phpsymfonyphpunitsymfony-formsdomcrawler

How to get the form object in PHPUnit


I am testing with the PHPUnit.

However it shows error.

whitebear$ phpunit -c app src/Acme/MemberBundle/Tests/Controller/DefaultControllerTest.php 
PHPUnit 4.8.35 by Sebastian Bergmann and contributors.

E

Time: 1.18 seconds, Memory: 90.25MB

There was 1 error:

1) Acme\MemberBundle\Tests\Controller\DefaultControllerTest::testIndex
InvalidArgumentException: The current node list is empty.

I guess there is something wrong with 'selectButton'.

$crawlerLogin = $client->request('GET', '/login');
$form = $crawlerLogin->selectButton('submit')->form();
$form['_username'] = 'myuser';
$form['_password'] = 'mypass'; 
$crawler = $client->submit($form);

These are html for testing generated by php.

<form action="/wisdom/web/app_dev.php/login_check" method="post">
            <input type="hidden" name="_csrf_token" value="fEIiYQbeYn-qt-siza3GKybh3RFSp5eOh-Nas5hyyh4" />

    <label for="username">Username</label>
    <input type="text" id="username" name="_username" value="" required="required" />

    <label for="password">Password</label>
    <input type="password" id="password" name="_password" required="required" />

    <input type="checkbox" id="remember_me" name="_remember_me" value="on" />
    <label for="remember_me">Remember me</label>

    <input type="submit" id="_submit" name="_submit" value="Log in" />
</form>

Solution

  • From the doc:

    selectButton() method is available on the Crawler which returns another Crawler that matches a button (input[type=submit], input[type=image], or a button) with the given text.

    You should pass the text of the button, so try with:

    $form = $crawlerLogin->selectButton('Log in')->form();
    

    Hope this help