Search code examples
phpsymfonytwigphpunitfunctional-testing

Functional testing with phpunit 6.5.1 symfony 3.4 button issue


I am trying to test my small web app with phpunit but Im having difficulty submitting forms and accessing the buttons with the crawler. I can't seem to login as the node always reports as empty. I believe the issue may be with the submit button, possibly trying to reference it.

private $client = null;

 public function setUp()
 {
    $this->client = static::createClient();
    $this->testlogIn();
 }

   public function testLogIn()
{
    $crawler = $this->client->request('GET', '/login');
    $form = $crawler->filter('button#logIn')
      ->form(
            [
              '_username' => 'AdminAccountKyleTest',
              '_password' => 'test'
            ],
            'POST'
        );

    $this->client->submit($form);

    $this->assertContains('Homepage', $crawler->filter('body > div.main > div > div > div:nth-child(2) > h1')->text());
}    

This is the twig template for the button:

  <button class="btn btn-lg btn-primary btn-block" id="logIn" 
type="submit">Sign in</button>

Does phpunit have an issue when the button is rendered in the twig instead of a SubmitType on a form ?


Solution

  • Test you form using the following snippet:

        //selectButton accepts the button id|name|text
        $form = $crawler->selectButton("logIn")->form();
    
        $form['_username'] = 'AdminAccountKyleTest';
        $form['_password'] = 'test';
    
        $client->submit($form);
    
        //follow the form request redirect after login_check
        $client->followRedirect();