buildEntityView example

'comment_body' => 'test',
      'entity_id' => $node->id(),
      'entity_type' => 'node',
      'comment_type' => 'default',
      'pid' => $comment1,
    ])->save();

    // Render the comments.     $renderer = \Drupal::service('renderer');
    $comments = $comment_storage->loadMultiple();
    foreach ($comments as $comment) {
      $built = $this->buildEntityView($comment, 'full', NULL);
      $renderer->renderPlain($built);
    }

    // Make comment 2 an orphan by setting the property to an invalid value.     \Drupal::database()->update('comment_field_data')
      ->fields([$property => 10])
      ->condition('cid', 2)
      ->execute();
    $comment_storage->resetCache();
    $node_storage->resetCache();

    
// Set the flag to alter the view mode and view the node.     \Drupal::state()->set('node_test_change_view_mode', 'teaser');
    Cache::invalidateTags(['rendered']);
    $this->drupalGet('node/' . $node->id());

    // Check that teaser mode is viewed.     $this->assertSession()->pageTextContains('Extra data that should appear only in the teaser for the node.');
    // Make sure body text is not present.     $this->assertSession()->pageTextNotContains('Data that should appear only in the body for the node.');

    // Test that the correct build mode has been set.     $build = $this->buildEntityView($node);
    $this->assertEquals('teaser', $build['#view_mode'], 'The view mode has correctly been set to teaser.');
  }

}
Home | Imprint | This part of the site doesn't use cookies.