NodeEntityViewModeAlterTest.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Drupal\Tests\node\Functional;
  3. use Drupal\Core\Cache\Cache;
  4. use Drupal\Tests\EntityViewTrait;
  5. /**
  6. * Tests changing view modes for nodes.
  7. *
  8. * @group node
  9. */
  10. class NodeEntityViewModeAlterTest extends NodeTestBase {
  11. use EntityViewTrait;
  12. /**
  13. * Enable dummy module that implements hook_ENTITY_TYPE_view() for nodes.
  14. */
  15. public static $modules = ['node_test'];
  16. /**
  17. * Create a "Basic page" node and verify its consistency in the database.
  18. */
  19. public function testNodeViewModeChange() {
  20. $web_user = $this->drupalCreateUser(['create page content', 'edit own page content']);
  21. $this->drupalLogin($web_user);
  22. // Create a node.
  23. $edit = [];
  24. $edit['title[0][value]'] = $this->randomMachineName(8);
  25. $edit['body[0][value]'] = t('Data that should appear only in the body for the node.');
  26. $edit['body[0][summary]'] = t('Extra data that should appear only in the teaser for the node.');
  27. $this->drupalPostForm('node/add/page', $edit, t('Save'));
  28. $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
  29. // Set the flag to alter the view mode and view the node.
  30. \Drupal::state()->set('node_test_change_view_mode', 'teaser');
  31. Cache::invalidateTags(['rendered']);
  32. $this->drupalGet('node/' . $node->id());
  33. // Check that teaser mode is viewed.
  34. $this->assertText('Extra data that should appear only in the teaser for the node.', 'Teaser text present');
  35. // Make sure body text is not present.
  36. $this->assertNoText('Data that should appear only in the body for the node.', 'Body text not present');
  37. // Test that the correct build mode has been set.
  38. $build = $this->buildEntityView($node);
  39. $this->assertEqual($build['#view_mode'], 'teaser', 'The view mode has correctly been set to teaser.');
  40. }
  41. }