You are here

public function AttachedAssetsTest::testSettings in Drupal 10

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Asset/AttachedAssetsTest.php \Drupal\KernelTests\Core\Asset\AttachedAssetsTest::testSettings()
  2. 9 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 195

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
    ->assertSame('yarhar', $parsed_settings['path']['pathPrefix'], 'drupalSettings.path.pathPrefix is present and has the correct (overridden) value.');
  $this
    ->assertSame('', $parsed_settings['path']['currentPath'], 'drupalSettings.path.currentPath is present and has the correct value.');
  $this
    ->assertFalse($parsed_settings['path']['currentPathIsAdmin'], 'drupalSettings.path.currentPathIsAdmin is present and has the correct value.');
  $this
    ->assertFalse($parsed_settings['path']['isFront'], 'drupalSettings.path.isFront is present and has the correct value.');
  $this
    ->assertSame('en', $parsed_settings['path']['currentLanguage'], '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
    ->assertSame('☃', $parsed_settings['pluralDelimiter']);
  $this
    ->assertSame('bar', $parsed_settings['foo']);
}