简体   繁体   中英

Symfony 4 Functional Form Test with CSRF Token and Session

I am using a symfony 4.4 with the form bundle and want to make some functional tests.

My form has multiple steps and I want to perform a complete form until the success message. But with csrf_protection:true I can't even get to page 2. If I disable it for the test environment I can get to page 2. If I dump my session at page 2, I can see, that it is empty. Here is an example of my test:

$client = static::createClient();
$client->request('GET', '/test');
$crawler = $client->submitForm('Next', ['name' => 'Max Mustermann']); // => lands on step2
$crawler = $client->submitForm('Next', ['email' => 'asdf@ase.de']); // => lands back on step 1 with emtpy form. So session is empty

Does anyone have an idea what is wrong here? This page says, that is have to work, but it doesn't. https://symfony.com/doc/4.4/components/http_foundation/session_testing.html#functional-testing

I suggest you to retrieve the form from the client's response then submit the form with the data, as example:

// Get the crawler
$crawler = $client->request('GET', '/test');

// Get the form
$form = $crawler->filter('form')->form();

// Fill the form. NB: double check your form structure/fields name
$form['name'] = 'Max Mustermann';
$form['email'] = 'asdf@ase.de';

// Submit the form.
$crawler = $this->client->submit($form);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM