function TimestampFormatterTest::testTimestampAgoFormatter

Same name and namespace in other branches
  1. 9 core/modules/field/tests/src/Kernel/Timestamp/TimestampFormatterTest.php \Drupal\Tests\field\Kernel\Timestamp\TimestampFormatterTest::testTimestampAgoFormatter()
  2. 8.9.x core/modules/field/tests/src/Kernel/Timestamp/TimestampFormatterTest.php \Drupal\Tests\field\Kernel\Timestamp\TimestampFormatterTest::testTimestampAgoFormatter()
  3. 10 core/modules/field/tests/src/Kernel/Timestamp/TimestampFormatterTest.php \Drupal\Tests\field\Kernel\Timestamp\TimestampFormatterTest::testTimestampAgoFormatter()

Tests TimestampAgoFormatter.

File

core/modules/field/tests/src/Kernel/Timestamp/TimestampFormatterTest.php, line 147

Class

TimestampFormatterTest
Tests the timestamp formatters.

Namespace

Drupal\Tests\field\Kernel\Timestamp

Code

public function testTimestampAgoFormatter() : void {
  foreach (range(1, 7) as $granularity) {
    $request_time = \Drupal::requestStack()->getCurrentRequest()->server
      ->get('REQUEST_TIME');
    // Test a timestamp in the past
    $value = $request_time - 87654321;
    $interval = \Drupal::service('date.formatter')->formatTimeDiffSince($value, [
      'granularity' => $granularity,
    ]);
    $expected = $interval . ' ago';
    $component = $this->display
      ->getComponent($this->fieldName);
    $component['type'] = 'timestamp_ago';
    $component['settings'] = [
      'granularity' => $granularity,
    ];
    $this->display
      ->setComponent($this->fieldName, $component);
    $entity = EntityTest::create([]);
    $entity->{$this->fieldName}->value = $value;
    $this->renderEntityFields($entity, $this->display);
    $this->assertRaw($expected);
    // Test a timestamp in the future
    $value = $request_time + 87654321;
    $interval = \Drupal::service('date.formatter')->formatTimeDiffUntil($value, [
      'granularity' => $granularity,
    ]);
    $expected = $interval . ' hence';
    $component = $this->display
      ->getComponent($this->fieldName);
    $component['type'] = 'timestamp_ago';
    $component['settings'] = [
      'granularity' => $granularity,
    ];
    $this->display
      ->setComponent($this->fieldName, $component);
    $entity = EntityTest::create([]);
    $entity->{$this->fieldName}->value = $value;
    $this->renderEntityFields($entity, $this->display);
    $this->assertRaw($expected);
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.