You are here

public function AttachedAssetsTest::testRenderOrder 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::testRenderOrder()

Tests JavaScript and CSS asset ordering.

File

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

Class

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

Namespace

Drupal\KernelTests\Core\Asset

Code

public function testRenderOrder() {
  $build['#attached']['library'][] = 'common_test/order';
  $assets = AttachedAssets::createFromRenderArray($build);

  // Construct the expected result from the regex.
  $expected_order_js = [
    "-8_1",
    "-8_2",
    "-8_3",
    "-8_4",
    // The external script.
    "-5_1",
    "-3_1",
    "-3_2",
    "0_1",
    "0_2",
    "0_3",
  ];

  // Retrieve the rendered JavaScript and test against the regex.
  $js = $this->assetResolver
    ->getJsAssets($assets, FALSE)[1];
  $js_render_array = \Drupal::service('asset.js.collection_renderer')
    ->render($js);
  $rendered_js = $this->renderer
    ->renderPlain($js_render_array);
  $matches = [];
  if (preg_match_all('/weight_([-0-9]+_[0-9]+)/', $rendered_js, $matches)) {
    $result = $matches[1];
  }
  else {
    $result = [];
  }
  $this
    ->assertIdentical($result, $expected_order_js, 'JavaScript is added in the expected weight order.');

  // Construct the expected result from the regex.
  $expected_order_css = [
    // Base.
    'base_weight_-101_1',
    'base_weight_-8_1',
    'layout_weight_-101_1',
    'base_weight_0_1',
    'base_weight_0_2',
    // Layout.
    'layout_weight_-8_1',
    'component_weight_-101_1',
    'layout_weight_0_1',
    'layout_weight_0_2',
    // Component.
    'component_weight_-8_1',
    'state_weight_-101_1',
    'component_weight_0_1',
    'component_weight_0_2',
    // State.
    'state_weight_-8_1',
    'theme_weight_-101_1',
    'state_weight_0_1',
    'state_weight_0_2',
    // Theme.
    'theme_weight_-8_1',
    'theme_weight_0_1',
    'theme_weight_0_2',
  ];

  // Retrieve the rendered CSS and test against the regex.
  $css = $this->assetResolver
    ->getCssAssets($assets, FALSE);
  $css_render_array = \Drupal::service('asset.css.collection_renderer')
    ->render($css);
  $rendered_css = $this->renderer
    ->renderPlain($css_render_array);
  $matches = [];
  if (preg_match_all('/([a-z]+)_weight_([-0-9]+_[0-9]+)/', $rendered_css, $matches)) {
    $result = $matches[0];
  }
  else {
    $result = [];
  }
  $this
    ->assertIdentical($result, $expected_order_css, 'CSS is added in the expected weight order.');
}