function LinksetControllerTest::testCacheability

Same name and namespace in other branches
  1. 10 core/modules/system/tests/src/Functional/Menu/LinksetControllerTest.php \Drupal\Tests\system\Functional\Menu\LinksetControllerTest::testCacheability()

Test the cacheability of the linkset endpoint.

This test's purpose is to ensure that the menu linkset response is properly cached. It does this by sending a request and validating it has a cache miss and the correct cacheability meta, then by sending the same request to assert a cache hit. Finally, a new menu item is created to ensure that the cached response is properly invalidated.

File

core/modules/system/tests/src/Functional/Menu/LinksetControllerTest.php, line 178

Class

LinksetControllerTest
Tests the behavior of the linkset controller.

Namespace

Drupal\Tests\system\Functional\Menu

Code

public function testCacheability() : void {
    $this->enableEndpoint(TRUE);
    $expected_cacheability = new CacheableMetadata();
    $expected_cacheability->addCacheContexts([
        'user.permissions',
    ]);
    $expected_cacheability->addCacheTags([
        'config:system.menu.main',
        'config:user.role.anonymous',
        'http_response',
        'node:1',
        'node:2',
        'node:3',
    ]);
    $response = $this->doRequest('GET', Url::fromUri('base:/system/menu/main/linkset'));
    $this->assertDrupalResponseCacheability('MISS', $expected_cacheability, $response);
    $response = $this->doRequest('GET', Url::fromUri('base:/system/menu/main/linkset'));
    $this->assertDrupalResponseCacheability('HIT', $expected_cacheability, $response);
    // Create a new menu item to invalidate the cache.
    $duplicate_title = 'About us (duplicate)';
    $this->createMenuItem([
        'title' => $duplicate_title,
        'description' => 'Links to the about us page again.',
        'link' => 'entity:node/1',
        'menu_name' => 'main',
    ]);
    // Redo the request.
    $response = $this->doRequest('GET', Url::fromUri('base:/system/menu/main/linkset'));
    // Assert that the cache has been invalidated.
    $this->assertDrupalResponseCacheability('MISS', $expected_cacheability, $response);
    // Then ensure that the new menu link is in the response.
    $link_items = Json::decode((string) $response->getBody())['linkset'][0]['item'];
    $titles = array_column($link_items, 'title');
    $this->assertContains($duplicate_title, $titles);
}

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