class JavaScriptTestCase

Tests for the JavaScript system.

Hierarchy

Expanded class hierarchy of JavaScriptTestCase

File

drupal/modules/simpletest/tests/common.test, line 1390
Tests for common.inc functionality.

View source
class JavaScriptTestCase extends DrupalWebTestCase {

  /**
   * Store configured value for JavaScript preprocessing.
   */
  protected $preprocess_js = NULL;
  public static function getInfo() {
    return array(
      'name' => 'JavaScript',
      'description' => 'Tests the JavaScript system.',
      'group' => 'System',
    );
  }
  function setUp() {

    // Enable Locale and SimpleTest in the test environment.
    parent::setUp('locale', 'simpletest', 'common_test');

    // Disable preprocessing
    $this->preprocess_js = variable_get('preprocess_js', 0);
    variable_set('preprocess_js', 0);

    // Reset drupal_add_js() and drupal_add_library() statics before each test.
    drupal_static_reset('drupal_add_js');
    drupal_static_reset('drupal_add_library');
  }
  function tearDown() {

    // Restore configured value for JavaScript preprocessing.
    variable_set('preprocess_js', $this->preprocess_js);
    parent::tearDown();
  }

  /**
   * Test default JavaScript is empty.
   */
  function testDefault() {
    $this
      ->assertEqual(array(), drupal_add_js(), 'Default JavaScript is empty.');
  }

  /**
   * Test adding a JavaScript file.
   */
  function testAddFile() {
    $javascript = drupal_add_js('misc/collapse.js');
    $this
      ->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when a file is added.');
    $this
      ->assertTrue(array_key_exists('misc/drupal.js', $javascript), 'Drupal.js is added when file is added.');
    $this
      ->assertTrue(array_key_exists('misc/collapse.js', $javascript), 'JavaScript files are correctly added.');
    $this
      ->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], 'Base path JavaScript setting is correctly set.');
    url('', array(
      'prefix' => &$prefix,
    ));
    $this
      ->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], 'Path prefix JavaScript setting is correctly set.');
  }

  /**
   * Test adding settings.
   */
  function testAddSetting() {
    $javascript = drupal_add_js(array(
      'drupal' => 'rocks',
      'dries' => 280342800,
    ), 'setting');
    $this
      ->assertEqual(280342800, $javascript['settings']['data'][2]['dries'], 'JavaScript setting is set correctly.');
    $this
      ->assertEqual('rocks', $javascript['settings']['data'][2]['drupal'], 'The other JavaScript setting is set correctly.');
  }

  /**
   * Tests adding an external JavaScript File.
   */
  function testAddExternal() {
    $path = 'http://example.com/script.js';
    $javascript = drupal_add_js($path, 'external');
    $this
      ->assertTrue(array_key_exists('http://example.com/script.js', $javascript), 'Added an external JavaScript file.');
  }

  /**
   * Test drupal_get_js() for JavaScript settings.
   */
  function testHeaderSetting() {

    // Only the second of these two entries should appear in Drupal.settings.
    drupal_add_js(array(
      'commonTest' => 'commonTestShouldNotAppear',
    ), 'setting');
    drupal_add_js(array(
      'commonTest' => 'commonTestShouldAppear',
    ), 'setting');

    // All three of these entries should appear in Drupal.settings.
    drupal_add_js(array(
      'commonTestArray' => array(
        'commonTestValue0',
      ),
    ), 'setting');
    drupal_add_js(array(
      'commonTestArray' => array(
        'commonTestValue1',
      ),
    ), 'setting');
    drupal_add_js(array(
      'commonTestArray' => array(
        'commonTestValue2',
      ),
    ), 'setting');

    // Only the second of these two entries should appear in Drupal.settings.
    drupal_add_js(array(
      'commonTestArray' => array(
        'key' => 'commonTestOldValue',
      ),
    ), 'setting');
    drupal_add_js(array(
      'commonTestArray' => array(
        'key' => 'commonTestNewValue',
      ),
    ), 'setting');
    $javascript = drupal_get_js('header');
    $this
      ->assertTrue(strpos($javascript, 'basePath') > 0, 'Rendered JavaScript header returns basePath setting.');
    $this
      ->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, 'Rendered JavaScript header includes jQuery.');
    $this
      ->assertTrue(strpos($javascript, 'pathPrefix') > 0, 'Rendered JavaScript header returns pathPrefix setting.');

    // Test whether drupal_add_js can be used to override a previous setting.
    $this
      ->assertTrue(strpos($javascript, 'commonTestShouldAppear') > 0, 'Rendered JavaScript header returns custom setting.');
    $this
      ->assertTrue(strpos($javascript, 'commonTestShouldNotAppear') === FALSE, 'drupal_add_js() correctly overrides a custom setting.');

    // Test whether drupal_add_js can be used to add numerically indexed values
    // to an array.
    $array_values_appear = strpos($javascript, 'commonTestValue0') > 0 && strpos($javascript, 'commonTestValue1') > 0 && strpos($javascript, 'commonTestValue2') > 0;
    $this
      ->assertTrue($array_values_appear, 'drupal_add_js() correctly adds settings to the end of an indexed array.');

    // Test whether drupal_add_js can be used to override the entry for an
    // existing key in an associative array.
    $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
    $this
      ->assertTrue($associative_array_override, 'drupal_add_js() correctly overrides settings within an associative array.');
  }

  /**
   * Test to see if resetting the JavaScript empties the cache.
   */
  function testReset() {
    drupal_add_js('misc/collapse.js');
    drupal_static_reset('drupal_add_js');
    $this
      ->assertEqual(array(), drupal_add_js(), 'Resetting the JavaScript correctly empties the cache.');
  }

  /**
   * Test adding inline scripts.
   */
  function testAddInline() {
    $inline = 'jQuery(function () { });';
    $javascript = drupal_add_js($inline, array(
      'type' => 'inline',
      'scope' => 'footer',
    ));
    $this
      ->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when inline scripts are added.');
    $data = end($javascript);
    $this
      ->assertEqual($inline, $data['data'], 'Inline JavaScript is correctly added to the footer.');
  }

  /**
   * Test rendering an external JavaScript file.
   */
  function testRenderExternal() {
    $external = 'http://example.com/example.js';
    drupal_add_js($external, 'external');
    $javascript = drupal_get_js();

    // Local files have a base_path() prefix, external files should not.
    $this
      ->assertTrue(strpos($javascript, 'src="' . $external) > 0, 'Rendering an external JavaScript file.');
  }

  /**
   * Test drupal_get_js() with a footer scope.
   */
  function testFooterHTML() {
    $inline = 'jQuery(function () { });';
    drupal_add_js($inline, array(
      'type' => 'inline',
      'scope' => 'footer',
    ));
    $javascript = drupal_get_js('footer');
    $this
      ->assertTrue(strpos($javascript, $inline) > 0, 'Rendered JavaScript footer returns the inline code.');
  }

  /**
   * Test the 'javascript_always_use_jquery' variable.
   */
  function testJavaScriptAlwaysUseJQuery() {

    // The default front page of the site should use jQuery and other standard
    // scripts and settings.
    $this
      ->drupalGet('');
    $this
      ->assertRaw('misc/jquery.js', 'Default behavior: The front page of the site includes jquery.js.');
    $this
      ->assertRaw('misc/drupal.js', 'Default behavior: The front page of the site includes drupal.js.');
    $this
      ->assertRaw('Drupal.settings', 'Default behavior: The front page of the site includes Drupal settings.');
    $this
      ->assertRaw('basePath', 'Default behavior: The front page of the site includes the basePath Drupal setting.');

    // The default front page should not use jQuery and other standard scripts
    // and settings when the 'javascript_always_use_jquery' variable is set to
    // FALSE.
    variable_set('javascript_always_use_jquery', FALSE);
    $this
      ->drupalGet('');
    $this
      ->assertNoRaw('misc/jquery.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include jquery.js.');
    $this
      ->assertNoRaw('misc/drupal.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include drupal.js.');
    $this
      ->assertNoRaw('Drupal.settings', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include Drupal settings.');
    $this
      ->assertNoRaw('basePath', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include the basePath Drupal setting.');
    variable_del('javascript_always_use_jquery');

    // When only settings have been added via drupal_add_js(), drupal_get_js()
    // should still return jQuery and other standard scripts and settings.
    $this
      ->resetStaticVariables();
    drupal_add_js(array(
      'testJavaScriptSetting' => 'test',
    ), 'setting');
    $javascript = drupal_get_js();
    $this
      ->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes jquery.js.');
    $this
      ->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes drupal.js.');
    $this
      ->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes Drupal.settings.');
    $this
      ->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes the basePath Drupal setting.');
    $this
      ->assertTrue(strpos($javascript, 'testJavaScriptSetting') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes the added Drupal settings.');

    // When only settings have been added via drupal_add_js() and the
    // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
    // should not return jQuery and other standard scripts and settings, nor
    // should it return the requested settings (since they cannot actually be
    // addded to the page without jQuery).
    $this
      ->resetStaticVariables();
    variable_set('javascript_always_use_jquery', FALSE);
    drupal_add_js(array(
      'testJavaScriptSetting' => 'test',
    ), 'setting');
    $javascript = drupal_get_js();
    $this
      ->assertTrue(strpos($javascript, 'misc/jquery.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include jquery.js.');
    $this
      ->assertTrue(strpos($javascript, 'misc/drupal.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include drupal.js.');
    $this
      ->assertTrue(strpos($javascript, 'Drupal.settings') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include Drupal.settings.');
    $this
      ->assertTrue(strpos($javascript, 'basePath') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include the basePath Drupal setting.');
    $this
      ->assertTrue(strpos($javascript, 'testJavaScriptSetting') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include the added Drupal settings.');
    variable_del('javascript_always_use_jquery');

    // When a regular file has been added via drupal_add_js(), drupal_get_js()
    // should return jQuery and other standard scripts and settings.
    $this
      ->resetStaticVariables();
    drupal_add_js('misc/collapse.js');
    $javascript = drupal_get_js();
    $this
      ->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes jquery.js.');
    $this
      ->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes drupal.js.');
    $this
      ->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes Drupal.settings.');
    $this
      ->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the basePath Drupal setting.');
    $this
      ->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the custom file.');

    // When a regular file has been added via drupal_add_js() and the
    // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
    // should still return jQuery and other standard scripts and settings
    // (since the file is assumed to require jQuery by default).
    $this
      ->resetStaticVariables();
    variable_set('javascript_always_use_jquery', FALSE);
    drupal_add_js('misc/collapse.js');
    $javascript = drupal_get_js();
    $this
      ->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes jquery.js.');
    $this
      ->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes drupal.js.');
    $this
      ->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes Drupal.settings.');
    $this
      ->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the basePath Drupal setting.');
    $this
      ->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the custom file.');
    variable_del('javascript_always_use_jquery');

    // When a file that does not require jQuery has been added via
    // drupal_add_js(), drupal_get_js() should still return jQuery and other
    // standard scripts and settings by default.
    $this
      ->resetStaticVariables();
    drupal_add_js('misc/collapse.js', array(
      'requires_jquery' => FALSE,
    ));
    $javascript = drupal_get_js();
    $this
      ->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes jquery.js.');
    $this
      ->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes drupal.js.');
    $this
      ->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes Drupal.settings.');
    $this
      ->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the basePath Drupal setting.');
    $this
      ->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the custom file.');

    // When a file that does not require jQuery has been added via
    // drupal_add_js() and the 'javascript_always_use_jquery' variable is set
    // to FALSE, drupal_get_js() should not return jQuery and other standard
    // scripts and setting, but it should still return the requested file.
    $this
      ->resetStaticVariables();
    variable_set('javascript_always_use_jquery', FALSE);
    drupal_add_js('misc/collapse.js', array(
      'requires_jquery' => FALSE,
    ));
    $javascript = drupal_get_js();
    $this
      ->assertTrue(strpos($javascript, 'misc/jquery.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include jquery.js.');
    $this
      ->assertTrue(strpos($javascript, 'misc/drupal.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include drupal.js.');
    $this
      ->assertTrue(strpos($javascript, 'Drupal.settings') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include Drupal.settings.');
    $this
      ->assertTrue(strpos($javascript, 'basePath') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include the basePath Drupal setting.');
    $this
      ->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the custom file.');
    variable_del('javascript_always_use_jquery');

    // When 'javascript_always_use_jquery' is set to FALSE and a file that does
    // not require jQuery is added, followed by one that does, drupal_get_js()
    // should return jQuery and other standard scripts and settings, in
    // addition to both of the requested files.
    $this
      ->resetStaticVariables();
    variable_set('javascript_always_use_jquery', FALSE);
    drupal_add_js('misc/collapse.js', array(
      'requires_jquery' => FALSE,
    ));
    drupal_add_js('misc/ajax.js');
    $javascript = drupal_get_js();
    $this
      ->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes jquery.js.');
    $this
      ->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes drupal.js.');
    $this
      ->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes Drupal.settings.');
    $this
      ->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the basePath Drupal setting.');
    $this
      ->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the first custom file.');
    $this
      ->assertTrue(strpos($javascript, 'misc/ajax.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the second custom file.');
    variable_del('javascript_always_use_jquery');
  }

  /**
   * Test drupal_add_js() sets preproccess to false when cache is set to false.
   */
  function testNoCache() {
    $javascript = drupal_add_js('misc/collapse.js', array(
      'cache' => FALSE,
    ));
    $this
      ->assertFalse($javascript['misc/collapse.js']['preprocess'], 'Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.');
  }

  /**
   * Test adding a JavaScript file with a different group.
   */
  function testDifferentGroup() {
    $javascript = drupal_add_js('misc/collapse.js', array(
      'group' => JS_THEME,
    ));
    $this
      ->assertEqual($javascript['misc/collapse.js']['group'], JS_THEME, 'Adding a JavaScript file with a different group caches the given group.');
  }

  /**
   * Test adding a JavaScript file with a different weight.
   */
  function testDifferentWeight() {
    $javascript = drupal_add_js('misc/collapse.js', array(
      'weight' => 2,
    ));
    $this
      ->assertEqual($javascript['misc/collapse.js']['weight'], 2, 'Adding a JavaScript file with a different weight caches the given weight.');
  }

  /**
   * Tests JavaScript aggregation when files are added to a different scope.
   */
  function testAggregationOrder() {

    // Enable JavaScript aggregation.
    variable_set('preprocess_js', 1);
    drupal_static_reset('drupal_add_js');

    // Add two JavaScript files to the current request and build the cache.
    drupal_add_js('misc/ajax.js');
    drupal_add_js('misc/autocomplete.js');
    $js_items = drupal_add_js();
    drupal_build_js_cache(array(
      'misc/ajax.js' => $js_items['misc/ajax.js'],
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js'],
    ));

    // Store the expected key for the first item in the cache.
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
    $expected_key = $cache[0];

    // Reset variables and add a file in a different scope first.
    variable_del('drupal_js_cache_files');
    drupal_static_reset('drupal_add_js');
    drupal_add_js('some/custom/javascript_file.js', array(
      'scope' => 'footer',
    ));
    drupal_add_js('misc/ajax.js');
    drupal_add_js('misc/autocomplete.js');

    // Rebuild the cache.
    $js_items = drupal_add_js();
    drupal_build_js_cache(array(
      'misc/ajax.js' => $js_items['misc/ajax.js'],
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js'],
    ));

    // Compare the expected key for the first file to the current one.
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
    $key = $cache[0];
    $this
      ->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
  }

  /**
   * Test JavaScript ordering.
   */
  function testRenderOrder() {

    // Add a bunch of JavaScript in strange ordering.
    drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array(
      'type' => 'inline',
      'scope' => 'footer',
      'weight' => 5,
    ));
    drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array(
      'type' => 'inline',
      'scope' => 'footer',
    ));
    drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array(
      'type' => 'inline',
      'scope' => 'footer',
    ));
    drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array(
      'type' => 'inline',
      'scope' => 'footer',
      'weight' => -8,
    ));
    drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array(
      'type' => 'inline',
      'scope' => 'footer',
      'weight' => -8,
    ));
    drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array(
      'type' => 'inline',
      'scope' => 'footer',
      'weight' => -8,
    ));
    drupal_add_js('http://example.com/example.js?Weight -5 #1', array(
      'type' => 'external',
      'scope' => 'footer',
      'weight' => -5,
    ));
    drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array(
      'type' => 'inline',
      'scope' => 'footer',
      'weight' => -8,
    ));
    drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array(
      'type' => 'inline',
      'scope' => 'footer',
      'weight' => 5,
    ));
    drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array(
      'type' => 'inline',
      'scope' => 'footer',
    ));

    // Construct the expected result from the regex.
    $expected = array(
      "-8 #1",
      "-8 #2",
      "-8 #3",
      "-8 #4",
      "-5 #1",
      // The external script.
      "0 #1",
      "0 #2",
      "0 #3",
      "5 #1",
      "5 #2",
    );

    // Retrieve the rendered JavaScript and test against the regex.
    $js = drupal_get_js('footer');
    $matches = array();
    if (preg_match_all('/Weight\\s([-0-9]+\\s[#0-9]+)/', $js, $matches)) {
      $result = $matches[1];
    }
    else {
      $result = array();
    }
    $this
      ->assertIdentical($result, $expected, 'JavaScript is added in the expected weight order.');
  }

  /**
   * Test rendering the JavaScript with a file's weight above jQuery's.
   */
  function testRenderDifferentWeight() {

    // JavaScript files are sorted first by group, then by the 'every_page'
    // flag, then by weight (see drupal_sort_css_js()), so to test the effect of
    // weight, we need the other two options to be the same.
    drupal_add_js('misc/collapse.js', array(
      'group' => JS_LIBRARY,
      'every_page' => TRUE,
      'weight' => -21,
    ));
    $javascript = drupal_get_js();
    $this
      ->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), 'Rendering a JavaScript file above jQuery.');
  }

  /**
   * Test altering a JavaScript's weight via hook_js_alter().
   *
   * @see simpletest_js_alter()
   */
  function testAlter() {

    // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
    drupal_add_js('misc/tableselect.js');
    drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array(
      'weight' => 9999,
    ));

    // Render the JavaScript, testing if simpletest.js was altered to be before
    // tableselect.js. See simpletest_js_alter() to see where this alteration
    // takes place.
    $javascript = drupal_get_js();
    $this
      ->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), 'Altering JavaScript weight through the alter hook.');
  }

  /**
   * Adds a library to the page and tests for both its JavaScript and its CSS.
   */
  function testLibraryRender() {
    $result = drupal_add_library('system', 'farbtastic');
    $this
      ->assertTrue($result !== FALSE, 'Library was added without errors.');
    $scripts = drupal_get_js();
    $styles = drupal_get_css();
    $this
      ->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'JavaScript of library was added to the page.');
    $this
      ->assertTrue(strpos($styles, 'misc/farbtastic/farbtastic.css'), 'Stylesheet of library was added to the page.');
  }

  /**
   * Adds a JavaScript library to the page and alters it.
   *
   * @see common_test_library_alter()
   */
  function testLibraryAlter() {

    // Verify that common_test altered the title of Farbtastic.
    $library = drupal_get_library('system', 'farbtastic');
    $this
      ->assertEqual($library['title'], 'Farbtastic: Altered Library', 'Registered libraries were altered.');

    // common_test_library_alter() also added a dependency on jQuery Form.
    drupal_add_library('system', 'farbtastic');
    $scripts = drupal_get_js();
    $this
      ->assertTrue(strpos($scripts, 'misc/jquery.form.js'), 'Altered library dependencies are added to the page.');
  }

  /**
   * Tests that multiple modules can implement the same library.
   *
   * @see common_test_library()
   */
  function testLibraryNameConflicts() {
    $farbtastic = drupal_get_library('common_test', 'farbtastic');
    $this
      ->assertEqual($farbtastic['title'], 'Custom Farbtastic Library', 'Alternative libraries can be added to the page.');
  }

  /**
   * Tests non-existing libraries.
   */
  function testLibraryUnknown() {
    $result = drupal_get_library('unknown', 'unknown');
    $this
      ->assertFalse($result, 'Unknown library returned FALSE.');
    drupal_static_reset('drupal_get_library');
    $result = drupal_add_library('unknown', 'unknown');
    $this
      ->assertFalse($result, 'Unknown library returned FALSE.');
    $scripts = drupal_get_js();
    $this
      ->assertTrue(strpos($scripts, 'unknown') === FALSE, 'Unknown library was not added to the page.');
  }

  /**
   * Tests the addition of libraries through the #attached['library'] property.
   */
  function testAttachedLibrary() {
    $element['#attached']['library'][] = array(
      'system',
      'farbtastic',
    );
    drupal_render($element);
    $scripts = drupal_get_js();
    $this
      ->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'The attached_library property adds the additional libraries.');
  }

  /**
   * Tests retrieval of libraries via drupal_get_library().
   */
  function testGetLibrary() {

    // Retrieve all libraries registered by a module.
    $libraries = drupal_get_library('common_test');
    $this
      ->assertTrue(isset($libraries['farbtastic']), 'Retrieved all module libraries.');

    // Retrieve all libraries for a module not implementing hook_library().
    // Note: This test installs Locale module.
    $libraries = drupal_get_library('locale');
    $this
      ->assertEqual($libraries, array(), 'Retrieving libraries from a module not implementing hook_library() returns an emtpy array.');

    // Retrieve a specific library by module and name.
    $farbtastic = drupal_get_library('common_test', 'farbtastic');
    $this
      ->assertEqual($farbtastic['version'], '5.3', 'Retrieved a single library.');

    // Retrieve a non-existing library by module and name.
    $farbtastic = drupal_get_library('common_test', 'foo');
    $this
      ->assertIdentical($farbtastic, FALSE, 'Retrieving a non-existing library returns FALSE.');
  }

  /**
   * Tests that the query string remains intact when adding JavaScript files
   *  that have query string parameters.
   */
  function testAddJsFileWithQueryString() {
    $this
      ->drupalGet('common-test/query-string');
    $query_string = variable_get('css_js_query_string', '0');
    $this
      ->assertRaw(drupal_get_path('module', 'node') . '/node.js?' . $query_string, 'Query string was appended correctly to js.');
  }

  /**
   * Resets static variables related to adding JavaScript to a page.
   */
  function resetStaticVariables() {
    drupal_static_reset('drupal_add_js');
    drupal_static_reset('drupal_add_library');
    drupal_static_reset('drupal_get_library');
  }

}

Members

Name Modifierssort descending Type Description Overrides
JavaScriptTestCase::setUp function Sets up a Drupal site for running functional and integration tests. Overrides DrupalWebTestCase::setUp
JavaScriptTestCase::tearDown function Delete created files and temporary files directory, delete the tables created by setUp(), and reset the database prefix. Overrides DrupalWebTestCase::tearDown
JavaScriptTestCase::testDefault function Test default JavaScript is empty.
JavaScriptTestCase::testAddFile function Test adding a JavaScript file.
JavaScriptTestCase::testAddSetting function Test adding settings.
JavaScriptTestCase::testAddExternal function Tests adding an external JavaScript File.
JavaScriptTestCase::testHeaderSetting function Test drupal_get_js() for JavaScript settings.
JavaScriptTestCase::testReset function Test to see if resetting the JavaScript empties the cache.
JavaScriptTestCase::testAddInline function Test adding inline scripts.
JavaScriptTestCase::testRenderExternal function Test rendering an external JavaScript file.
JavaScriptTestCase::testFooterHTML function Test drupal_get_js() with a footer scope.
JavaScriptTestCase::testNoCache function Test drupal_add_js() sets preproccess to false when cache is set to false.
JavaScriptTestCase::testDifferentGroup function Test adding a JavaScript file with a different group.
JavaScriptTestCase::testDifferentWeight function Test adding a JavaScript file with a different weight.
JavaScriptTestCase::testAggregationOrder function Tests JavaScript aggregation when files are added to a different scope.
JavaScriptTestCase::testRenderOrder function Test JavaScript ordering.
JavaScriptTestCase::testRenderDifferentWeight function Test rendering the JavaScript with a file's weight above jQuery's.
JavaScriptTestCase::testAlter function Test altering a JavaScript's weight via hook_js_alter().
JavaScriptTestCase::testLibraryRender function Adds a library to the page and tests for both its JavaScript and its CSS.
JavaScriptTestCase::testLibraryAlter function Adds a JavaScript library to the page and alters it.
JavaScriptTestCase::testLibraryNameConflicts function Tests that multiple modules can implement the same library.
JavaScriptTestCase::testLibraryUnknown function Tests non-existing libraries.
JavaScriptTestCase::testAttachedLibrary function Tests the addition of libraries through the #attached['library'] property.
JavaScriptTestCase::testGetLibrary function Tests retrieval of libraries via drupal_get_library().
JavaScriptTestCase::testAddJsFileWithQueryString function Tests that the query string remains intact when adding JavaScript files that have query string parameters.
JavaScriptTestCase::testJavaScriptAlwaysUseJQuery function Test the 'javascript_always_use_jquery' variable.
JavaScriptTestCase::resetStaticVariables function Resets static variables related to adding JavaScript to a page.
DrupalWebTestCase::__construct function Constructor for DrupalWebTestCase. Overrides DrupalTestCase::__construct 1
DrupalWebTestCase::drupalGetNodeByTitle function Get a node from the database based on its title.
DrupalWebTestCase::drupalCreateNode protected function Creates a node based on default settings.
DrupalWebTestCase::drupalCreateContentType protected function Creates a custom content type based on default settings.
DrupalWebTestCase::drupalGetTestFiles protected function Get a list files that can be used in tests.
DrupalWebTestCase::drupalCompareFiles protected function Compare two files based on size and file name.
DrupalWebTestCase::drupalCreateUser protected function Create a user with a given set of permissions.
DrupalWebTestCase::drupalCreateRole protected function Creates a role with specified permissions.
DrupalWebTestCase::checkPermissions protected function Check to make sure that the array of permissions are valid.
DrupalWebTestCase::drupalLogin protected function Log in a user with the internal browser.
DrupalWebTestCase::drupalGetToken protected function Generate a token for the currently logged in user.
DrupalWebTestCase::drupalLogout protected function
DrupalWebTestCase::prepareDatabasePrefix protected function Generates a database prefix for running tests.
DrupalWebTestCase::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
DrupalWebTestCase::prepareEnvironment protected function Prepares the current environment for running the test.
DrupalWebTestCase::preloadRegistry protected function Preload the registry from the testing site.
DrupalWebTestCase::resetAll protected function Reset all data structures after having enabled new modules.
DrupalWebTestCase::refreshVariables protected function Refresh the in-memory set of variables. Useful after a page request is made that changes a variable in a different thread. 1
DrupalWebTestCase::curlInitialize protected function Initializes the cURL connection.
DrupalWebTestCase::curlExec protected function Initializes and executes a cURL request.
DrupalWebTestCase::curlHeaderCallback protected function Reads headers and registers errors received from the tested site.
DrupalWebTestCase::curlClose protected function Close the cURL handler and unset the handler.
DrupalWebTestCase::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
DrupalWebTestCase::drupalGet protected function Retrieves a Drupal path or an absolute path.
DrupalWebTestCase::drupalGetAJAX protected function Retrieve a Drupal path or an absolute path and JSON decode the result.
DrupalWebTestCase::drupalPost protected function Execute a POST request on a Drupal page. It will be done as usual POST request with SimpleBrowser.
DrupalWebTestCase::drupalPostAJAX protected function Execute an Ajax submission.
DrupalWebTestCase::cronRun protected function Runs cron in the Drupal installed by Simpletest.
DrupalWebTestCase::checkForMetaRefresh protected function Check for meta refresh tag and if found call drupalGet() recursively. This function looks for the http-equiv attribute to be set to "Refresh" and is case-sensitive.
DrupalWebTestCase::drupalHead protected function Retrieves only the headers for a Drupal path or an absolute path.
DrupalWebTestCase::handleForm protected function Handle form input related to drupalPost(). Ensure that the specified fields exist and attempt to create POST data in the correct manner for the particular field type.
DrupalWebTestCase::buildXPathQuery protected function Builds an XPath query.
DrupalWebTestCase::xpath protected function Perform an xpath search on the contents of the internal browser. The search is relative to the root element (HTML tag normally) of the page.
DrupalWebTestCase::getAllOptions protected function Get all option elements, including nested options, in a select.
DrupalWebTestCase::assertLink protected function Pass if a link with the specified label is found, and optional with the specified index.
DrupalWebTestCase::assertNoLink protected function Pass if a link with the specified label is not found.
DrupalWebTestCase::assertLinkByHref protected function Pass if a link containing a given href (part) is found.
DrupalWebTestCase::assertNoLinkByHref protected function Pass if a link containing a given href (part) is not found.
DrupalWebTestCase::clickLink protected function Follows a link by name.
DrupalWebTestCase::getAbsoluteUrl protected function Takes a path and returns an absolute path.
DrupalWebTestCase::getUrl protected function Get the current URL from the cURL handler.
DrupalWebTestCase::drupalGetHeaders protected function Gets the HTTP response headers of the requested page. Normally we are only interested in the headers returned by the last request. However, if a page is redirected or HTTP authentication is in use, multiple requests will be required to retrieve the…
DrupalWebTestCase::drupalGetHeader protected function Gets the value of an HTTP response header. If multiple requests were required to retrieve the page, only the headers from the last request will be checked by default. However, if TRUE is passed as the second argument, all requests will be processed…
DrupalWebTestCase::drupalGetContent protected function Gets the current raw HTML of requested page.
DrupalWebTestCase::drupalGetSettings protected function Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::drupalGetMails protected function Gets an array containing all e-mails sent during this test case.
DrupalWebTestCase::drupalSetContent protected function Sets the raw HTML content. This can be useful when a page has been fetched outside of the internal browser and assertions need to be made on the returned page.
DrupalWebTestCase::drupalSetSettings protected function Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::assertUrl protected function Pass if the internal browser's URL matches the given path.
DrupalWebTestCase::assertRaw protected function Pass if the raw text IS found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertNoRaw protected function Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertText protected function Pass if the text IS found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertNoText protected function Pass if the text is NOT found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertTextHelper protected function Helper for assertText and assertNoText.
DrupalWebTestCase::assertUniqueText protected function Pass if the text is found ONLY ONCE on the text version of the page.
DrupalWebTestCase::assertNoUniqueText protected function Pass if the text is found MORE THAN ONCE on the text version of the page.
DrupalWebTestCase::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
DrupalWebTestCase::assertPattern protected function Will trigger a pass if the Perl regex pattern is found in the raw content.
DrupalWebTestCase::assertNoPattern protected function Will trigger a pass if the perl regex pattern is not present in raw content.
DrupalWebTestCase::assertTitle protected function Pass if the page title is the given string.
DrupalWebTestCase::assertNoTitle protected function Pass if the page title is not the given string.
DrupalWebTestCase::assertThemeOutput protected function Asserts themed output.
DrupalWebTestCase::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
DrupalWebTestCase::getSelectedItem protected function Get the selected value from a select field.
DrupalWebTestCase::assertNoFieldByXPath protected function Asserts that a field doesn't exist or its value doesn't match, by XPath.
DrupalWebTestCase::assertFieldByName protected function Asserts that a field exists in the current page with the given name and value.
DrupalWebTestCase::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
DrupalWebTestCase::assertFieldById protected function Asserts that a field exists in the current page with the given ID and value.
DrupalWebTestCase::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
DrupalWebTestCase::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
DrupalWebTestCase::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
DrupalWebTestCase::assertOptionSelected protected function Asserts that a select option in the current page is checked.
DrupalWebTestCase::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
DrupalWebTestCase::assertField protected function Asserts that a field exists with the given name or ID.
DrupalWebTestCase::assertNoField protected function Asserts that a field does not exist with the given name or ID.
DrupalWebTestCase::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
DrupalWebTestCase::constructFieldXpath protected function Helper function: construct an XPath for the given set of attributes and value.
DrupalWebTestCase::assertResponse protected function Asserts the page responds with the specified response code.
DrupalWebTestCase::assertNoResponse protected function Asserts the page did not return the specified response code.
DrupalWebTestCase::assertMail protected function Asserts that the most recently sent e-mail message has the given value.
DrupalWebTestCase::assertMailString protected function Asserts that the most recently sent e-mail message has the string in it.
DrupalWebTestCase::assertMailPattern protected function Asserts that the most recently sent e-mail message has the pattern in it.
DrupalWebTestCase::verboseEmail protected function Outputs to verbose the most recent $count emails sent.
DrupalTestCase::assert protected function Internal helper: stores the assert.
DrupalTestCase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
DrupalTestCase::assertTrue protected function Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertFalse protected function Check to see if a value is false (an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertNull protected function Check to see if a value is NULL.
DrupalTestCase::assertNotNull protected function Check to see if a value is not NULL.
DrupalTestCase::assertEqual protected function Check to see if two values are equal.
DrupalTestCase::assertNotEqual protected function Check to see if two values are not equal.
DrupalTestCase::assertIdentical protected function Check to see if two values are identical.
DrupalTestCase::assertNotIdentical protected function Check to see if two values are not identical.
DrupalTestCase::pass protected function Fire an assertion that is always positive.
DrupalTestCase::fail protected function Fire an assertion that is always negative.
DrupalTestCase::error protected function Fire an error assertion. 1
DrupalTestCase::verbose protected function Logs a verbose message in a text file.
DrupalTestCase::exceptionHandler protected function Handle exceptions.
JavaScriptTestCase::$preprocess_js protected property Store configured value for JavaScript preprocessing.
DrupalWebTestCase::$profile protected property The profile to install as a basis for testing. 20
DrupalWebTestCase::$url protected property The URL currently loaded in the internal browser.
DrupalWebTestCase::$curlHandle protected property The handle of the current cURL connection.
DrupalWebTestCase::$headers protected property The headers of the page currently loaded in the internal browser.
DrupalWebTestCase::$content protected property The content of the page currently loaded in the internal browser.
DrupalWebTestCase::$plainTextContent protected property The content of the page currently loaded in the internal browser (plain text version).
DrupalWebTestCase::$drupalSettings protected property The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
DrupalWebTestCase::$elements protected property The parsed version of the page.
DrupalWebTestCase::$loggedInUser protected property The current user logged in using the internal browser.
DrupalWebTestCase::$cookieFile protected property The current cookie file used by cURL.
DrupalWebTestCase::$additionalCurlOptions protected property Additional cURL options.
DrupalWebTestCase::$originalUser protected property The original user, before it was changed to a clean uid = 1 for testing purposes.
DrupalWebTestCase::$originalShutdownCallbacks protected property The original shutdown handlers array, before it was cleaned for testing purposes.
DrupalWebTestCase::$httpauth_method protected property HTTP authentication method
DrupalWebTestCase::$httpauth_credentials protected property HTTP authentication credentials (<username>:<password>).
DrupalWebTestCase::$session_name protected property The current session name, if available.
DrupalWebTestCase::$session_id protected property The current session ID, if available.
DrupalWebTestCase::$generatedTestFiles protected property Whether the files were copied to the test files directory.
DrupalWebTestCase::$redirect_count protected property The number of redirects followed during the handling of a request.
DrupalWebTestCase::$cookies protected property The cookies of the page currently loaded in the internal browser.
DrupalTestCase::$testId protected property The test run ID.
DrupalTestCase::$databasePrefix protected property The database prefix of this test run.
DrupalTestCase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
DrupalTestCase::$timeLimit protected property Time limit for the test.
DrupalTestCase::$assertions protected property Assertions thrown in that test case.
DrupalTestCase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
DrupalTestCase::$setup protected property Flag to indicate whether the test has been set up.
DrupalTestCase::$setupDatabasePrefix protected property
DrupalTestCase::$setupEnvironment protected property
DrupalTestCase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
DrupalTestCase::run public function Run all tests in this class.
DrupalTestCase::errorHandler public function Handle errors during test runs. 1
DrupalTestCase::$results public property Current results of this test case.
JavaScriptTestCase::getInfo public static function
DrupalTestCase::insertAssert public static function Store an assertion from outside the testing context.
DrupalTestCase::deleteAssert public static function Delete an assertion record by message ID.
DrupalTestCase::randomString public static function Generates a random string of ASCII characters of codes 32 to 126.
DrupalTestCase::randomName public static function Generates a random string containing letters and numbers.
DrupalTestCase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
DrupalTestCase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.