You are here

public function ResponsiveImageFieldDisplayTest::testResponsiveImageFieldFormattersOneSource in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/responsive_image/tests/src/Functional/ResponsiveImageFieldDisplayTest.php \Drupal\Tests\responsive_image\Functional\ResponsiveImageFieldDisplayTest::testResponsiveImageFieldFormattersOneSource()
  2. 9 core/modules/responsive_image/tests/src/Functional/ResponsiveImageFieldDisplayTest.php \Drupal\Tests\responsive_image\Functional\ResponsiveImageFieldDisplayTest::testResponsiveImageFieldFormattersOneSource()

Tests responsive image formatter on node display with one source.

File

core/modules/responsive_image/tests/src/Functional/ResponsiveImageFieldDisplayTest.php, line 421

Class

ResponsiveImageFieldDisplayTest
Tests responsive image display formatter.

Namespace

Drupal\Tests\responsive_image\Functional

Code

public function testResponsiveImageFieldFormattersOneSource() {
  $this->responsiveImgStyle
    ->addImageStyleMapping('responsive_image_test_module.empty', '1x', [
    'image_mapping_type' => 'image_style',
    'image_mapping' => 'medium',
  ])
    ->addImageStyleMapping('responsive_image_test_module.empty', '2x', [
    'image_mapping_type' => 'image_style',
    'image_mapping' => 'large',
  ])
    ->save();
  $node_storage = $this->container
    ->get('entity_type.manager')
    ->getStorage('node');
  $field_name = mb_strtolower($this
    ->randomMachineName());
  $this
    ->createImageField($field_name, 'article', [
    'uri_scheme' => 'public',
  ]);

  // Create a new node with an image attached.
  $test_image = current($this
    ->getTestFiles('image'));
  $nid = $this
    ->uploadNodeImage($test_image, $field_name, 'article', $this
    ->randomMachineName());
  $node_storage
    ->resetCache([
    $nid,
  ]);

  // Use the responsive image formatter linked to file formatter.
  $display_options = [
    'type' => 'responsive_image',
    'settings' => [
      'image_link' => '',
      'responsive_image_style' => 'style_one',
    ],
  ];
  $display = \Drupal::service('entity_display.repository')
    ->getViewDisplay('node', 'article');
  $display
    ->setComponent($field_name, $display_options)
    ->save();

  // View the node.
  $this
    ->drupalGet('node/' . $nid);

  // Assert the media attribute is present if it has a value.
  $large_style = ImageStyle::load('large');
  $medium_style = ImageStyle::load('medium');
  $node = $node_storage
    ->load($nid);
  $image_uri = File::load($node->{$field_name}->target_id)
    ->getFileUri();
  $this
    ->assertSession()
    ->responseContains('<img srcset="' . $this->fileUrlGenerator
    ->transformRelative($medium_style
    ->buildUrl($image_uri)) . ' 1x, ' . $this->fileUrlGenerator
    ->transformRelative($large_style
    ->buildUrl($image_uri)) . ' 2x"');
}