You are here

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

Tests the custom Add Comment resource.

File

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

Class

JsonapiResourceTest
Tests JSON:API Resource processors.

Namespace

Drupal\Tests\jsonapi_resources\Functional

Code

public function testAddCommentResource() {
  $this
    ->config('jsonapi.settings')
    ->set('read_only', FALSE)
    ->save(TRUE);
  $this
    ->grantPermissionsToTestedRole([
    'access content',
    'access comments',
    'post comments',
  ]);
  $author_user = $this->account;
  $node = Node::create([
    'type' => 'article',
    'title' => $this
      ->randomString(),
    'status' => 1,
    'uid' => $author_user
      ->id(),
  ]);
  $node
    ->save();
  $url = Url::fromUri(sprintf('internal:/jsonapi/comment/add'));
  $request_options = [];
  $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
  $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
  $request_options = NestedArray::mergeDeep($request_options, $this
    ->getAuthenticationRequestOptions());
  $request_options[RequestOptions::JSON] = [
    'data' => [
      'type' => 'comment--comment',
      'attributes' => [
        'entity_type' => 'node',
        'field_name' => 'comment',
        'subject' => 'Dramallama',
        'status' => 1,
        'comment_body' => [
          'value' => 'Llamas are awesome.',
          'format' => 'plain_text',
        ],
      ],
      'relationships' => [
        'entity_id' => [
          'data' => [
            'type' => 'node--article',
            'id' => $node
              ->uuid(),
          ],
        ],
      ],
    ],
  ];
  $response = $this
    ->request('POST', $url, $request_options);
  $this
    ->assertSame(201, $response
    ->getStatusCode(), $response
    ->getBody());
  $this
    ->assertTrue($response
    ->hasHeader('Location'));
  $created_url = Url::fromUri($response
    ->getHeader('Location')[0]);
  $response = $this
    ->request('GET', $created_url, $request_options);
  $this
    ->assertSame(200, $response
    ->getStatusCode(), $response
    ->getBody());
  $document = Json::decode((string) $response
    ->getBody());
  $exists = FALSE;
  $article_uuid = NestedArray::getValue($document, explode('/', 'data/relationships/entity_id/data/id'), $exists);
  $this
    ->assertTrue($exists);
  $this
    ->assertSame($node
    ->uuid(), $article_uuid);
}