You are here

public function StyleSerializerTest::testLivePreview in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/rest/tests/src/Functional/Views/StyleSerializerTest.php \Drupal\Tests\rest\Functional\Views\StyleSerializerTest::testLivePreview()
  2. 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 589

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 a 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
    ->assertArrayNotHasKey('#markup', $build);
  $this
    ->assertSame($expected, $rendered_json, '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
    ->assertEquals($expected, $rendered_xml, 'Ensure we preview xml when we change the request format.');
}