You are here

public function JsonapiResourceTest::testFeaturedNodesResource in JSON:API Resources 8

Tests the custom Featured Nodes resource.

File

tests/src/Functional/JsonapiResourceTest.php, line 156

Class

JsonapiResourceTest
Tests JSON:API Resource processors.

Namespace

Drupal\Tests\jsonapi_resources\Functional

Code

public function testFeaturedNodesResource() {
  $promoted_nodes = [];
  for ($i = 0; $i < 8; $i++) {
    $promoted = $i % 2 === 0;
    $node = Node::create([
      'type' => 'article',
      'title' => $this
        ->randomString(),
      'status' => 1,
      'promote' => $promoted ? 1 : 0,
    ]);
    $node
      ->save();
    if ($promoted) {
      $promoted_nodes[$node
        ->uuid()] = $node;
    }
  }
  $this
    ->grantPermissionsToTestedRole([
    'access content',
    'access user profiles',
  ]);
  $url = Url::fromUri('internal:/jsonapi/featured-content');
  $request_options = [];
  $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
  $request_options = NestedArray::mergeDeep($request_options, $this
    ->getAuthenticationRequestOptions());
  $response = $this
    ->request('GET', $url, $request_options);
  $this
    ->assertSame(200, $response
    ->getStatusCode(), var_export(Json::decode((string) $response
    ->getBody()), TRUE));
  $response_document = Json::decode((string) $response
    ->getBody());
  $this
    ->assertCount(4, $response_document['data']);
  $this
    ->assertSame(array_keys($promoted_nodes), array_map(static function (array $data) {
    return $data['id'];
  }, $response_document['data']));
}