You are here

public function ReferenceWidgetTest::testFormElement in Select (or other) 8.3

Same name and namespace in other branches
  1. 8 tests/src/Unit/ReferenceWidgetTest.php \Drupal\Tests\select_or_other\Unit\ReferenceWidgetTest::testFormElement()
  2. 4.x tests/src/Unit/ReferenceWidgetTest.php \Drupal\Tests\select_or_other\Unit\ReferenceWidgetTest::testFormElement()

Test if formElement() adds the expected information.

File

Tests/src/Unit/ReferenceWidgetTest.php, line 152

Class

ReferenceWidgetTest
Tests the form element implementation.

Namespace

Drupal\Tests\select_or_other\Unit

Code

public function testFormElement() {
  $userMock = $this
    ->getMock('User', [
    'id',
  ]);
  $userMock
    ->expects($this
    ->any())
    ->method('id')
    ->willReturn(1);
  $this->containerMock
    ->expects($this
    ->any())
    ->method('get')
    ->with('current_user')
    ->willReturn($userMock);
  foreach ([
    'node',
    'taxonomy_term',
  ] as $target_type) {

    /** @var ReferenceWidget $mock */
    $mock = $this
      ->prepareFormElementMock($target_type);

    /** @var SelectOrOtherWidgetBase $parent */
    $parent = $this
      ->prepareFormElementMock($target_type, 'Drupal\\select_or_other\\Plugin\\Field\\FieldWidget\\SelectOrOtherWidgetBase');
    $entity_class = $target_type === 'taxonomy_term' ? 'Drupal\\Core\\Entity\\EntityInterface' : 'Drupal\\user\\EntityOwnerInterface';
    $entity = $this
      ->getMockForAbstractClass($entity_class);
    $entity
      ->expects($this
      ->any())
      ->method('getOwnerId')
      ->willReturn(1);
    $items = $this
      ->getMockForAbstractClass('Drupal\\Core\\Field\\FieldItemListInterface');
    $items
      ->expects($this
      ->any())
      ->method('getEntity')
      ->willReturn($entity);

    /** @var FieldItemListInterface $items */
    $delta = 1;
    $element = [];
    $form = [];
    $form_state = new FormState();
    $parentResult = $parent
      ->formElement($items, $delta, $element, $form, $form_state);
    $result = $mock
      ->formElement($items, $delta, $element, $form, $form_state);
    $added = array_diff_key($result, $parentResult);
    $expected = [
      '#target_type' => $target_type,
      '#selection_handler' => 'some_handler',
      '#selection_settings' => [],
      '#autocreate' => [
        'bundle' => 'autoCreateBundle',
        'uid' => 1,
      ],
      '#validate_reference' => TRUE,
      '#tags' => $target_type === 'taxonomy_term',
      '#merged_values' => TRUE,
    ];
    $this
      ->assertArrayEquals($expected, $added);
  }
}