Symfony 4.2 will be released in November 2018. This is the first article of the series that shows the most important new features introduced by this Symfony version.


Viktor Novikov
Contributed by Viktor Novikov in #27807

In Symfony apps, functional tests use a PHP-based client provided by the BrowserKit component to simulate a browser and perform HTTP requests. In Symfony 4.2 we've introduced new helper methods in this client to simplify the action of clicking links and submitting forms.

First, the clickLink() helper clicks the first link that contains the given text (or the first clickable image whose alt attribute contains the given text):

1
2
3
4
5
6
7
8
// Before
$client->request('GET', '/');
$link = $crawler->selectLink('Login')->link();
$crawler = $client->click($link);

// After
$client->request('GET', '/');
$crawler = $client->clickLink('Login');

The previous way of dealing with links (with the selectLink() and click() methods) still works and you'll need to use it in more complex scenarios (for example when you need to access to some attribute of the link before clicking it).

The other new helper is called submitForm(), which finds the first form that contains a button with the given text (or id, value or name) and uses it to submit the given form field values:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Before
$client->request('GET', '/register');
$form = $crawler->selectButton('Sign Up')->form();
$crawler = $client->submit($form, [
    'name' => 'Jane Doe',
    'username' => 'jane',
    'password' => 'my safe password',
]);

// After
$client->request('GET', '/register');
$crawler = $client->submitForm('Sign Up', [
    'name' => 'Jane Doe',
    'username' => 'jane',
    'password' => 'my safe password',
]);

The previous way of dealing with forms (with the selectButton() and submit() methods) still works and you'll need to use it in more complex scenarios (for example when you need to access to some attribute of the form before submitting it).

Lastly, if you want to run your functional tests in a real browser instead of this simulated browser check out Symfony Panther, the latest addition to the Symfony ecosystem. One of its biggest advantages is that it uses the same API as BrowserKit, so you can use these new helpers in Panther too.

Published in #Living on the edge