You are here

public function HookTokensTest::testNodeSummaryTokenReplacement in Node Summary Token From P Tags 1.0.x

Same name and namespace in other branches
  1. 1.x tests/src/HookTokensTest.php \Drupal\Tests\node_summary_token_from_p\HookTokensTest::testNodeSummaryTokenReplacement()

Test if the normal [node:summary] token still works as required.

File

tests/src/HookTokensTest.php, line 87

Class

HookTokensTest

Namespace

Drupal\Tests\node_summary_token_from_p

Code

public function testNodeSummaryTokenReplacement() {

  // Create a user and a node.
  $account = $this
    ->createUser();

  /* @var $node \Drupal\node\NodeInterface */
  $node = Node::create([
    'type' => 'article',
    'tnid' => 0,
    'uid' => $account
      ->id(),
    'title' => 'Title',
    'body' => [
      [
        'value' => 'Regular NODE body for the test.',
        'summary' => 'Fancy NODE summary.',
        'format' => 'plain_text',
      ],
    ],
  ]);
  $node
    ->save();

  // Generate and test tokens.
  $tests = [];
  $tests['[node:summary]'] = $node->body->summary_processed;
  $base_bubbleable_metadata = BubbleableMetadata::createFromObject($node);
  $metadata_tests = [];
  $metadata_tests['[node:summary]'] = $base_bubbleable_metadata;

  // Test to make sure that we generated something for each token.
  $this
    ->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');
  foreach ($tests as $input => $expected) {
    $bubbleable_metadata = new BubbleableMetadata();
    $output = $this->tokenService
      ->replace($input, [
      'node' => $node,
    ], [
      'langcode' => $this->interfaceLanguage
        ->getId(),
    ], $bubbleable_metadata);
    $this
      ->assertEqual($output, $expected, new FormattableMarkup('Node token %token replaced.', [
      '%token' => $input,
    ]));
    $this
      ->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
  }

  // Repeat for a node without a summary.
  $node = Node::create([
    'type' => 'article',
    'uid' => $account
      ->id(),
    'title' => '<blink>Blinking Text</blink>',
    'body' => [
      [
        'value' => 'A string that looks random like TR5c2I',
        'format' => 'plain_text',
      ],
    ],
  ]);
  $node
    ->save();

  // Generate and test token - use full body as expected value.
  $tests = [];
  $tests['[node:summary]'] = $node->body->processed;

  // Test to make sure that we generated something for each token.
  $this
    ->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated for node without a summary.');
  foreach ($tests as $input => $expected) {
    $output = $this->tokenService
      ->replace($input, [
      'node' => $node,
    ], [
      'language' => $this->interfaceLanguage,
    ]);
    $this
      ->assertEqual($output, $expected, new FormattableMarkup('Node token %token replaced for node without a summary.', [
      '%token' => $input,
    ]));
  }
}