You are here

public function CommentInterfaceTest::testViewMode in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/comment/tests/src/Functional/CommentInterfaceTest.php \Drupal\Tests\comment\Functional\CommentInterfaceTest::testViewMode()

Tests the comment formatter configured with a custom comment view mode.

File

core/modules/comment/tests/src/Functional/CommentInterfaceTest.php, line 311

Class

CommentInterfaceTest
Tests comment user interfaces.

Namespace

Drupal\Tests\comment\Functional

Code

public function testViewMode() {
  $this
    ->drupalLogin($this->webUser);
  $this
    ->drupalGet($this->node
    ->toUrl());
  $comment_text = $this
    ->randomMachineName();

  // Post a comment.
  $this
    ->postComment($this->node, $comment_text);

  // Comment displayed in 'default' display mode found and has body text.
  $comment_element = $this
    ->cssSelect('.comment-wrapper');
  $this
    ->assertTrue(!empty($comment_element));
  $this
    ->assertSession()
    ->responseContains('<p>' . $comment_text . '</p>');

  // Create a new comment entity view mode.
  $mode = mb_strtolower($this
    ->randomMachineName());
  EntityViewMode::create([
    'targetEntityType' => 'comment',
    'id' => "comment.{$mode}",
  ])
    ->save();

  // Create the corresponding entity view display for article node-type. Note
  // that this new view display mode doesn't contain the comment body.
  EntityViewDisplay::create([
    'targetEntityType' => 'comment',
    'bundle' => 'comment',
    'mode' => $mode,
  ])
    ->setStatus(TRUE)
    ->save();

  /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $node_display */
  $node_display = EntityViewDisplay::load('node.article.default');
  $formatter = $node_display
    ->getComponent('comment');

  // Change the node comment field formatter to use $mode mode instead of
  // 'default' mode.
  $formatter['settings']['view_mode'] = $mode;
  $node_display
    ->setComponent('comment', $formatter)
    ->save();

  // Reloading the node page to show the same node with its same comment but
  // with a different display mode.
  $this
    ->drupalGet($this->node
    ->toUrl());

  // The comment should exist but without the body text because we used $mode
  // mode this time.
  $comment_element = $this
    ->cssSelect('.comment-wrapper');
  $this
    ->assertTrue(!empty($comment_element));
  $this
    ->assertSession()
    ->responseNotContains('<p>' . $comment_text . '</p>');
}