You are here

public function SiteAlertCacheWorkaroundTest::testPageCacheWorkaround in Site Alert 8

Tests that the workaround to display alerts on cached pages works.

File

tests/src/FunctionalJavascript/SiteAlertCacheWorkaroundTest.php, line 31

Class

SiteAlertCacheWorkaroundTest
Tests that the workaround for the core caching bug is working as expected.

Namespace

Drupal\Tests\site_alert\FunctionalJavascript

Code

public function testPageCacheWorkaround() {
  $this
    ->drupalPlaceBlock('site_alert_block', [
    'id' => 'site_alert_block',
    // Disable the timeout. Under normal circumstances this would disable AJAX
    // calls completely, but due to the caching bug we still need to load
    // alerts using JS.
    'timeout' => 0,
  ]);

  // Create a site alert that is scheduled to appear in a few seconds.
  $alert = SiteAlert::create([
    'active' => TRUE,
    'severity' => 'high',
    'message' => [
      'value' => 'Scheduled alert',
      'format' => 'plain_text',
    ],
    'label' => 'Scheduled',
    'scheduling' => [
      'value' => (new DrupalDateTime('+2 seconds', DateTimeItemInterface::STORAGE_TIMEZONE))
        ->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT),
    ],
  ]);
  $alert
    ->save();

  // Load the front page. The scheduled alert should not be visible yet.
  $this
    ->drupalGet('<front>');
  $this
    ->assertSiteAlertNotVisible('Scheduled alert');

  // Since the workaround is in effect, the JavaScript code that is
  // responsible for refreshing the alerts should be loaded in the page.
  $this
    ->assertJavaScriptPresent();

  // The automatic refreshing has been disabled by setting the 'timeout' to 0,
  // so the scheduled alert should not appear until we reload the page.
  $this
    ->assertSiteAlertNotAppears('Scheduled alert', 3000);

  // Reload the page. Thanks to the workaround the site alert should now
  // appear regardless of the fact that the page was cached at a moment when
  // no alert was visible.
  $this
    ->drupalGet('<front>');
  $this
    ->assertSiteAlertAppears('Scheduled alert');

  // Disable the alert. Now there are no more scheduled alerts, so the
  // workaround is not needed and the JS code should not be loaded.
  $alert
    ->set('active', FALSE)
    ->save();
  $this
    ->drupalGet('<front>');
  $this
    ->assertSiteAlertNotVisible('Scheduled alert');
  $this
    ->assertJavaScriptNotPresent();
}