function ImageThemeFunctionTest::testImageStyleTheme

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

Tests usage of the image style theme function.

File

core/modules/image/tests/src/Kernel/ImageThemeFunctionTest.php, line 149

Class

ImageThemeFunctionTest
Tests image theme functions.

Namespace

Drupal\Tests\image\Kernel

Code

public function testImageStyleTheme() : void {
    
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container
        ->get('renderer');
    // Create an image.
    $files = $this->drupalGetTestFiles('image');
    $file = reset($files);
    $original_uri = \Drupal::service('file_system')->copy($file->uri, 'public://', FileExists::Rename);
    // Create a style.
    $style = ImageStyle::create([
        'name' => 'image_test',
        'label' => 'Test',
    ]);
    $style->save();
    $url = \Drupal::service('file_url_generator')->transformRelative($style->buildUrl($original_uri));
    // Create the base element that we'll use in the tests below.
    $base_element = [
        '#theme' => 'image_style',
        '#style_name' => 'image_test',
        '#uri' => $original_uri,
    ];
    $element = $base_element;
    $this->setRawContent($renderer->renderRoot($element));
    $elements = $this->xpath('//img[@src=:url and @alt=""]', [
        ':url' => $url,
    ]);
    $this->assertCount(1, $elements, 'theme_image_style() renders an image correctly.');
    // Test using theme_image_style() with a NULL value for the alt option.
    $element = $base_element;
    $element['#alt'] = NULL;
    $this->setRawContent($renderer->renderRoot($element));
    $elements = $this->xpath('//img[@src=:url]', [
        ':url' => $url,
    ]);
    $this->assertCount(1, $elements, 'theme_image_style() renders an image correctly with a NULL value for the alt option.');
}

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