You are here

public function AttachedAssetsTest::testSettings in Drupal 8

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Asset/AttachedAssetsTest.php \Drupal\KernelTests\Core\Asset\AttachedAssetsTest::testSettings()
  2. 10 core/tests/Drupal/KernelTests/Core/Asset/AttachedAssetsTest.php \Drupal\KernelTests\Core\Asset\AttachedAssetsTest::testSettings()

Tests JavaScript settings.

File

core/tests/Drupal/KernelTests/Core/Asset/AttachedAssetsTest.php, line 188

Class

AttachedAssetsTest
Tests #attached assets: attached asset libraries and JavaScript settings.

Namespace

Drupal\KernelTests\Core\Asset

Code

public function testSettings() {
  $build = [];
  $build['#attached']['library'][] = 'core/drupalSettings';

  // Nonsensical value to verify if it's possible to override path settings.
  $build['#attached']['drupalSettings']['path']['pathPrefix'] = 'yarhar';
  $assets = AttachedAssets::createFromRenderArray($build);
  $js = $this->assetResolver
    ->getJsAssets($assets, FALSE)[1];
  $js_render_array = \Drupal::service('asset.js.collection_renderer')
    ->render($js);

  // Cast to string since this returns a \Drupal\Core\Render\Markup object.
  $rendered_js = (string) $this->renderer
    ->renderPlain($js_render_array);

  // Parse the generated drupalSettings <script> back to a PHP representation.
  $startToken = '{';
  $endToken = '}';
  $start = strpos($rendered_js, $startToken);
  $end = strrpos($rendered_js, $endToken);

  // Convert to a string, as $renderer_js is a \Drupal\Core\Render\Markup
  // object.
  $json = mb_substr($rendered_js, $start, $end - $start + 1);
  $parsed_settings = Json::decode($json);

  // Test whether the settings for core/drupalSettings are available.
  $this
    ->assertTrue(isset($parsed_settings['path']['baseUrl']), 'drupalSettings.path.baseUrl is present.');
  $this
    ->assertIdentical($parsed_settings['path']['pathPrefix'], 'yarhar', 'drupalSettings.path.pathPrefix is present and has the correct (overridden) value.');
  $this
    ->assertIdentical($parsed_settings['path']['currentPath'], '', 'drupalSettings.path.currentPath is present and has the correct value.');
  $this
    ->assertIdentical($parsed_settings['path']['currentPathIsAdmin'], FALSE, 'drupalSettings.path.currentPathIsAdmin is present and has the correct value.');
  $this
    ->assertIdentical($parsed_settings['path']['isFront'], FALSE, 'drupalSettings.path.isFront is present and has the correct value.');
  $this
    ->assertIdentical($parsed_settings['path']['currentLanguage'], 'en', 'drupalSettings.path.currentLanguage is present and has the correct value.');

  // Tests whether altering JavaScript settings via hook_js_settings_alter()
  // is working as expected.
  // @see common_test_js_settings_alter()
  $this
    ->assertIdentical($parsed_settings['pluralDelimiter'], '☃');
  $this
    ->assertIdentical($parsed_settings['foo'], 'bar');
}