function JavaScriptTest::testAggregation

Tests JavaScript grouping and aggregation.

File

drupal/core/modules/system/lib/Drupal/system/Tests/Common/JavaScriptTest.php, line 289
Definition of Drupal\system\Tests\Common\JavaScriptTest.

Class

JavaScriptTest
Tests the JavaScript system.

Namespace

Drupal\system\Tests\Common

Code

function testAggregation() {
  $default_query_string = variable_get('css_js_query_string', '0');

  // To optimize aggregation, items with the 'every_page' option are ordered
  // ahead of ones without. The order of JavaScript execution must be the
  // same regardless of whether aggregation is enabled, so ensure this
  // expected order, first with aggregation off.
  drupal_add_library('system', 'drupal');
  drupal_add_js('core/misc/ajax.js');
  drupal_add_js('core/misc/collapse.js', array(
    'every_page' => TRUE,
  ));
  drupal_add_js('core/misc/autocomplete.js');
  drupal_add_js('core/misc/batch.js', array(
    'every_page' => TRUE,
  ));
  $javascript = drupal_get_js();
  $expected = implode("\n", array(
    '<script src="' . file_create_url('core/misc/collapse.js') . '?' . $default_query_string . '"></script>',
    '<script src="' . file_create_url('core/misc/batch.js') . '?' . $default_query_string . '"></script>',
    '<script src="' . file_create_url('core/misc/ajax.js') . '?' . $default_query_string . '"></script>',
    '<script src="' . file_create_url('core/misc/autocomplete.js') . '?' . $default_query_string . '"></script>',
  ));
  $this
    ->assertTrue(strpos($javascript, $expected) > 0, 'Unaggregated JavaScript is added in the expected group order.');

  // Now ensure that with aggregation on, one file is made for the
  // 'every_page' files, and one file is made for the others.
  drupal_static_reset('drupal_add_js');
  $config = config('system.performance');
  $config
    ->set('js.preprocess', 1);
  $config
    ->save();
  drupal_add_library('system', 'drupal');
  drupal_add_js('core/misc/ajax.js');
  drupal_add_js('core/misc/collapse.js', array(
    'every_page' => TRUE,
  ));
  drupal_add_js('core/misc/autocomplete.js');
  drupal_add_js('core/misc/batch.js', array(
    'every_page' => TRUE,
  ));
  $js_items = drupal_add_js();
  $javascript = drupal_get_js();
  $expected = implode("\n", array(
    '<script src="' . file_create_url(drupal_build_js_cache(array(
      'core/misc/collapse.js' => $js_items['core/misc/collapse.js'],
      'core/misc/batch.js' => $js_items['core/misc/batch.js'],
    ))) . '"></script>',
    '<script src="' . file_create_url(drupal_build_js_cache(array(
      'core/misc/ajax.js' => $js_items['core/misc/ajax.js'],
      'core/misc/autocomplete.js' => $js_items['core/misc/autocomplete.js'],
    ))) . '"></script>',
  ));
  $this
    ->assertTrue(strpos($javascript, $expected) !== FALSE, 'JavaScript is aggregated in the expected groups and order.');
}