I am writing unittests for my controllers that also handle form-submits.
everything is working fine so far. I am using the library laminas-test to dispatch the requests.
Now I added a csrf-element to my form but I don’t know how to get the csrf-token so that I am able to dispatch a request with a valid token to test this behaviour too.
Is there any way to do this with the component “laminas-test” or any other way?
You should can simulate page opened first, grab the body, and use regex to get csrf value, for example:
preg_match('/(?<=name="csrf" value=")(.{32})/', $body, $matches);
$formData = [
'csrf' => $matches[0],
// other fields here...
];
after it, use the $formData
variable to make new request with post method.
Thank you for your response.
Since phpunit is deleting all session-data after each test I ended up recreating the csrfToken with the same name before dispatching the requests so I always have the correct token and everything is working as expected.