function ImageFormatterTest::testImageFormatterUrlOptions

Same name in other branches
  1. 9 core/modules/image/tests/src/Kernel/ImageFormatterTest.php \Drupal\Tests\image\Kernel\ImageFormatterTest::testImageFormatterUrlOptions()
  2. 8.9.x core/modules/image/tests/src/Kernel/ImageFormatterTest.php \Drupal\Tests\image\Kernel\ImageFormatterTest::testImageFormatterUrlOptions()
  3. 10 core/modules/image/tests/src/Kernel/ImageFormatterTest.php \Drupal\Tests\image\Kernel\ImageFormatterTest::testImageFormatterUrlOptions()

Tests Image Formatter URL options handling.

File

core/modules/image/tests/src/Kernel/ImageFormatterTest.php, line 180

Class

ImageFormatterTest
Tests the image field rendering using entity fields of the image field type.

Namespace

Drupal\Tests\image\Kernel

Code

public function testImageFormatterUrlOptions() : void {
    $this->display
        ->setComponent($this->fieldName, [
        'settings' => [
            'image_link' => 'content',
        ],
    ]);
    // Create a test entity with the image field set.
    $entity = EntityTest::create([
        'name' => $this->randomMachineName(),
    ]);
    $entity->{$this->fieldName}
        ->generateSampleItems(2);
    $entity->save();
    // Generate the render array to verify URL options are as expected.
    $build = $this->display
        ->build($entity);
    $this->assertInstanceOf(Url::class, $build[$this->fieldName][0]['#url']);
    $build[$this->fieldName][0]['#url']
        ->setOption('attributes', [
        'data-attributes-test' => 'test123',
    ]);
    
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container
        ->get('renderer');
    $output = $renderer->renderRoot($build[$this->fieldName][0]);
    $this->assertStringContainsString('<a href="' . $entity->toUrl()
        ->toString() . '" data-attributes-test="test123"', (string) $output);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.