From 0db0214432a35cb46ce78b5e4f5442395dcdf3ad Mon Sep 17 00:00:00 2001 From: Tavo Nieves J <64917965+TavoNiievez@users.noreply.github.com> Date: Tue, 24 Nov 2020 11:33:01 -0500 Subject: [PATCH] Added seeFormErrorMessage function (#50) --- src/Codeception/Module/Symfony.php | 59 ++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/Codeception/Module/Symfony.php b/src/Codeception/Module/Symfony.php index b3049bd..68d0526 100644 --- a/src/Codeception/Module/Symfony.php +++ b/src/Codeception/Module/Symfony.php @@ -1108,6 +1108,65 @@ public function seeCurrentActionIs(string $action) $this->fail("Action '$action' does not exist"); } + /** + * Verifies that a form field has an error. + * You can specify the expected error message as second parameter. + * + * ``` php + * seeFormErrorMessage('username'); + * $I->seeFormErrorMessage('username', 'Username is empty'); + * ``` + * @param string $field + * @param string|null $message + */ + public function seeFormErrorMessage(string $field, $message = null) + { + $formCollector = $this->grabCollector('form', __FUNCTION__); + + if (!$forms = $formCollector->getData()->getValue('forms')['forms']) { + $this->fail('There are no forms on the current page.'); + } + + $fields = []; + $errors = []; + + foreach ($forms as $form) { + foreach ($form['children'] as $child) { + $fieldName = $child['name']; + $fields[] = $fieldName; + + if (!array_key_exists('errors', $child)) { + continue; + } + foreach ($child['errors'] as $error) { + $errors[$fieldName] = $error['message']; + } + } + } + + if (array_search($field, $fields) === false) { + $this->fail("the field '$field' does not exist in the form."); + } + + if (!array_key_exists($field, $errors)) { + $this->fail("No form error message for field '$field'."); + } + + if (!$message) { + return; + } + + $this->assertStringContainsString( + $message, + $errors[$field], + sprintf( + "There is an error message for the field '%s', but it does not match the expected message.", + $field + ) + ); + } + /** * Checks that the user's password would not benefit from rehashing. * If the user is not provided it is taken from the current session.