You are here

public function FormErrorHandlerTest::testErrorMessagesInline in Drupal 8

@covers ::handleFormErrors @covers ::displayErrorMessages @covers ::setElementErrorsFromFormState

File

core/modules/inline_form_errors/tests/src/Unit/FormErrorHandlerTest.php, line 120

Class

FormErrorHandlerTest
@coversDefaultClass \Drupal\inline_form_errors\FormErrorHandler @group InlineFormErrors

Namespace

Drupal\Tests\inline_form_errors\Unit

Code

public function testErrorMessagesInline() {
  $this->messenger
    ->expects($this
    ->at(0))
    ->method('addError')
    ->with('no title given');
  $this->messenger
    ->expects($this
    ->at(1))
    ->method('addError')
    ->with('element is invisible');
  $this->messenger
    ->expects($this
    ->at(2))
    ->method('addError')
    ->with('this missing element is invalid');
  $this->messenger
    ->expects($this
    ->at(3))
    ->method('addError')
    ->with('3 errors have been found: <ul-comma-list-mock><li-mock>Test 1</li-mock><li-mock>Test 2 &amp; a half</li-mock><li-mock>Test 3</li-mock></ul-comma-list-mock>');
  $this->renderer
    ->expects($this
    ->once())
    ->method('renderPlain')
    ->will($this
    ->returnCallback(function ($render_array) {
    $links = [];
    foreach ($render_array[1]['#items'] as $item) {
      $links[] = htmlspecialchars($item['#title']);
    }
    return $render_array[0]['#markup'] . '<ul-comma-list-mock><li-mock>' . implode('</li-mock><li-mock>', $links) . '</li-mock></ul-comma-list-mock>';
  }));
  $form_state = new FormState();
  $form_state
    ->setErrorByName('test1', 'invalid');
  $form_state
    ->setErrorByName('test2', 'invalid');
  $form_state
    ->setErrorByName('fieldset][test3', 'invalid');
  $form_state
    ->setErrorByName('test4', 'no error message');
  $form_state
    ->setErrorByName('test5', 'no title given');
  $form_state
    ->setErrorByName('test6', 'element is invisible');
  $form_state
    ->setErrorByName('missing_element', 'this missing element is invalid');
  $this->formErrorHandler
    ->handleFormErrors($this->testForm, $form_state);

  // Assert the #errors is populated for proper input.
  $this
    ->assertSame('invalid', $this->testForm['test1']['#errors']);
  $this
    ->assertSame('invalid', $this->testForm['test2']['#errors']);
  $this
    ->assertSame('invalid', $this->testForm['fieldset']['test3']['#errors']);
  $this
    ->assertSame('no error message', $this->testForm['test4']['#errors']);
  $this
    ->assertSame('no title given', $this->testForm['test5']['#errors']);
  $this
    ->assertSame('element is invisible', $this->testForm['test6']['#errors']);
}