You are here

public function StyleSerializerTest::testLivePreview in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/rest/tests/src/Functional/Views/StyleSerializerTest.php \Drupal\Tests\rest\Functional\Views\StyleSerializerTest::testLivePreview()

Tests the live preview output for json output.

File

core/modules/rest/tests/src/Functional/Views/StyleSerializerTest.php, line 588

Class

StyleSerializerTest
Tests the serializer style plugin.

Namespace

Drupal\Tests\rest\Functional\Views

Code

public function testLivePreview() {

  // We set up a request so it looks like an request in the live preview.
  $request = new Request();
  $request->query
    ->add([
    MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax',
  ]);

  /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
  $request_stack = \Drupal::service('request_stack');
  $request_stack
    ->push($request);
  $view = Views::getView('test_serializer_display_entity');
  $view
    ->setDisplay('rest_export_1');
  $this
    ->executeView($view);

  // Get the serializer service.
  $serializer = $this->container
    ->get('serializer');
  $entities = [];
  foreach ($view->result as $row) {
    $entities[] = $row->_entity;
  }
  $expected = $serializer
    ->serialize($entities, 'json');
  $view->live_preview = TRUE;
  $build = $view
    ->preview();
  $rendered_json = $build['#plain_text'];
  $this
    ->assertTrue(!isset($build['#markup']) && $rendered_json == $expected, 'Ensure the previewed json is escaped.');
  $view
    ->destroy();
  $expected = $serializer
    ->serialize($entities, 'xml');

  // Change the request format to xml.
  $view
    ->setDisplay('rest_export_1');
  $view
    ->getDisplay()
    ->setOption('style', [
    'type' => 'serializer',
    'options' => [
      'uses_fields' => FALSE,
      'formats' => [
        'xml' => 'xml',
      ],
    ],
  ]);
  $this
    ->executeView($view);
  $build = $view
    ->preview();
  $rendered_xml = $build['#plain_text'];
  $this
    ->assertEqual($rendered_xml, $expected, 'Ensure we preview xml when we change the request format.');
}