function CacheTest::testHeaderStorage

Same name in other branches
  1. 9 core/modules/views/tests/src/Kernel/Plugin/CacheTest.php \Drupal\Tests\views\Kernel\Plugin\CacheTest::testHeaderStorage()
  2. 8.9.x core/modules/views/tests/src/Kernel/Plugin/CacheTest.php \Drupal\Tests\views\Kernel\Plugin\CacheTest::testHeaderStorage()
  3. 10 core/modules/views/tests/src/Kernel/Plugin/CacheTest.php \Drupal\Tests\views\Kernel\Plugin\CacheTest::testHeaderStorage()

Tests css/js storage and restoring mechanism.

File

core/modules/views/tests/src/Kernel/Plugin/CacheTest.php, line 264

Class

CacheTest
Tests pluggable caching for views.

Namespace

Drupal\Tests\views\Kernel\Plugin

Code

public function testHeaderStorage() : void {
    // Create a view with output caching enabled.
    // Some hook_views_pre_render in views_test_data.module adds the test css/js file.
    // so they should be added to the css/js storage.
    $view = Views::getView('test_view');
    $view->setDisplay();
    $view->storage
        ->set('id', 'test_cache_header_storage');
    $view->display_handler
        ->overrideOption('cache', [
        'type' => 'time',
        'options' => [
            'output_lifespan' => '3600',
        ],
    ]);
    $output = $view->buildRenderable();
    
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');
    $renderer->executeInRenderContext(new RenderContext(), function () use (&$output, $renderer) {
        return $renderer->render($output);
    });
    unset($view->pre_render_called);
    $view->destroy();
    $view->setDisplay();
    $output = $view->buildRenderable();
    $renderer->executeInRenderContext(new RenderContext(), function () use (&$output, $renderer) {
        return $renderer->render($output);
    });
    $this->assertContains('views_test_data/test', $output['#attached']['library'], 'Make sure libraries are added for cached views.');
    $this->assertEquals([
        'foo' => 'bar',
    ], $output['#attached']['drupalSettings'], 'Make sure drupalSettings are added for cached views.');
    // Note: views_test_data_views_pre_render() adds some cache tags.
    $this->assertEquals([
        'config:views.view.test_cache_header_storage',
        'views_test_data:1',
    ], $output['#cache']['tags']);
    $this->assertEquals([
        'non-existing-placeholder-just-for-testing-purposes' => [
            '#lazy_builder' => [
                'Drupal\\views_test_data\\Controller\\ViewsTestDataController::placeholderLazyBuilder',
                [
                    'bar',
                ],
            ],
        ],
    ], $output['#attached']['placeholders']);
    $this->assertArrayNotHasKey('pre_render_called', $view->build_info, 'Make sure hook_views_pre_render is not called for the cached view.');
}

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