You are here

public function JsonapiMenuItemsTest::testJsonapiMenuItemsResource in JSON:API Menu Items 1.2.x

Same name and namespace in other branches
  1. 1.0.x tests/src/Functional/JsonapiMenuItemsTest.php \Drupal\Tests\jsonapi_menu_items\Functional\JsonapiMenuItemsTest::testJsonapiMenuItemsResource()
  2. 1.1.x tests/src/Functional/JsonapiMenuItemsTest.php \Drupal\Tests\jsonapi_menu_items\Functional\JsonapiMenuItemsTest::testJsonapiMenuItemsResource()

Tests the JSON:API Menu Items resource.

File

tests/src/Functional/JsonapiMenuItemsTest.php, line 67

Class

JsonapiMenuItemsTest
Tests JSON:API Menu Items functionality.

Namespace

Drupal\Tests\jsonapi_menu_items\Functional

Code

public function testJsonapiMenuItemsResource() {
  $link_title = $this
    ->randomMachineName();
  $content_link = $this
    ->createMenuLink($link_title, 'jsonapi_menu_test.open');
  $url = Url::fromRoute('jsonapi_menu_items.menu', [
    'menu' => 'jsonapi-menu-items-test',
  ]);
  [
    $content,
  ] = $this
    ->getJsonApiMenuItemsResponse($url);

  // There are 5 items in this menu - 4 from
  // jsonapi_menu_items_test.links.menu.yml and the content item created
  // above. One of the four in that file is disabled and should be filtered
  // out, another is not accesible to the current users. This leaves a total
  // of 3 items in the response.
  $this
    ->assertCount(3, $content['data']);
  $expected_items = Json::decode(strtr(file_get_contents(dirname(__DIR__, 2) . '/fixtures/expected-items.json'), [
    '%uuid' => $content_link
      ->uuid(),
    '%title' => $link_title,
    '%base_path' => Url::fromRoute('<front>')
      ->toString(),
  ]));
  $this
    ->assertEqual($expected_items['data'], $content['data']);

  // Assert response is cached with appropriate cacheability metadata such
  // that re-saving the link with a new title yields the new title in a
  // subsequent request.
  $new_title = $this
    ->randomMachineName();
  $content_link->title = $new_title;
  $content_link
    ->save();
  [
    $content,
  ] = $this
    ->getJsonApiMenuItemsResponse($url);
  $match = array_filter($content['data'], function (array $item) use ($content_link) {
    return $item['id'] === 'menu_link_content:' . $content_link
      ->uuid();
  });
  $this
    ->assertEqual($new_title, reset($match)['attributes']['title']);

  // Add another link and ensue cacheability metadata ensures the new item
  // appears in a subsequent request.
  $this
    ->createMenuLink($link_title, 'jsonapi_menu_test.open');
  [
    $content,
  ] = $this
    ->getJsonApiMenuItemsResponse($url);
  $this
    ->assertCount(4, $content['data']);
}