You are here

public function DisplayApiTest::testFieldEmpty in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/field/tests/src/Kernel/DisplayApiTest.php \Drupal\Tests\field\Kernel\DisplayApiTest::testFieldEmpty()

Tests that the prepareView() formatter method still fires for empty values.

File

core/modules/field/tests/src/Kernel/DisplayApiTest.php, line 289

Class

DisplayApiTest
Tests the field display API.

Namespace

Drupal\Tests\field\Kernel

Code

public function testFieldEmpty() {

  // Uses \Drupal\field_test\Plugin\Field\FieldFormatter\TestFieldEmptyFormatter.
  $display = [
    'label' => 'hidden',
    'type' => 'field_empty_test',
    'settings' => [
      'test_empty_string' => '**EMPTY FIELD**' . $this
        ->randomMachineName(),
    ],
  ];

  // $this->entity is set by the setUp() method and by default contains 4
  // numeric values.  We only want to test the display of this one field.
  $build = $this->entity
    ->get($this->fieldName)
    ->view($display);
  $this
    ->render($build);

  // The test field by default contains values, so should not display the
  // default "empty" text.
  $this
    ->assertNoText($display['settings']['test_empty_string']);

  // Now remove the values from the test field and retest.
  $this->entity->{$this->fieldName} = [];
  $this->entity
    ->save();
  $build = $this->entity
    ->get($this->fieldName)
    ->view($display);
  $this
    ->render($build);

  // This time, as the field values have been removed, we *should* show the
  // default "empty" text.
  $this
    ->assertText($display['settings']['test_empty_string']);
}