class AttachedAssetsTest

Same name and namespace in other branches
  1. 11.x core/tests/Drupal/KernelTests/Core/Asset/AttachedAssetsTest.php \Drupal\KernelTests\Core\Asset\AttachedAssetsTest
  2. 10 core/tests/Drupal/KernelTests/Core/Asset/AttachedAssetsTest.php \Drupal\KernelTests\Core\Asset\AttachedAssetsTest
  3. 9 core/tests/Drupal/KernelTests/Core/Asset/AttachedAssetsTest.php \Drupal\KernelTests\Core\Asset\AttachedAssetsTest
  4. 8.9.x core/tests/Drupal/KernelTests/Core/Asset/AttachedAssetsTest.php \Drupal\KernelTests\Core\Asset\AttachedAssetsTest

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

I.e. tests:


$build['#attached']['library'] = …
$build['#attached']['drupalSettings'] = …

Attributes

#[Group('Common')] #[Group('Asset')] #[RunTestsInSeparateProcesses]

Hierarchy

Expanded class hierarchy of AttachedAssetsTest

File

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

Namespace

Drupal\KernelTests\Core\Asset
View source
class AttachedAssetsTest extends KernelTestBase {
  
  /**
   * The asset resolver service.
   *
   * @var \Drupal\Core\Asset\AssetResolverInterface
   */
  protected $assetResolver;
  
  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;
  
  /**
   * The file URL generator.
   *
   * @var \Drupal\Core\File\FileUrlGeneratorInterface
   */
  protected $fileUrlGenerator;
  
  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'language',
    'common_test',
    'system',
  ];
  
  /**
   * {@inheritdoc}
   */
  protected function setUp() : void {
    parent::setUp();
    $this->assetResolver = $this->container
      ->get('asset.resolver');
    $this->renderer = $this->container
      ->get('renderer');
    $this->fileUrlGenerator = $this->container
      ->get('file_url_generator');
  }
  
  /**
   * Tests that default CSS and JavaScript is empty.
   */
  public function testDefault() : void {
    $assets = new AttachedAssets();
    $this->assertEquals([], $this->assetResolver
      ->getCssAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage()), 'Default CSS is empty.');
    [$js_assets_header, $js_assets_footer] = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage());
    $this->assertEquals([], $js_assets_header, 'Default header JavaScript is empty.');
    $this->assertEquals([], $js_assets_footer, 'Default footer JavaScript is empty.');
  }
  
  /**
   * Tests non-existing libraries.
   */
  public function testLibraryUnknown() : void {
    $build['#attached']['library'][] = 'core/unknown';
    $assets = AttachedAssets::createFromRenderArray($build);
    $this->assertSame([], $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[0], 'Unknown library was not added to the page.');
  }
  
  /**
   * Tests adding a CSS and a JavaScript file.
   */
  public function testAddFiles() : void {
    $build['#attached']['library'][] = 'common_test/files';
    $assets = AttachedAssets::createFromRenderArray($build);
    $css = $this->assetResolver
      ->getCssAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage());
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $this->assertArrayHasKey('core/modules/system/tests/modules/common_test/bar.css', $css);
    $this->assertArrayHasKey('core/modules/system/tests/modules/common_test/foo.js', $js);
    $css_render_array = \Drupal::service('asset.css.collection_renderer')->render($css);
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_css = (string) $this->renderer
      ->renderInIsolation($css_render_array);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    $query_string = $this->container
      ->get('asset.query_string')
      ->get();
    $this->assertStringContainsString('<link rel="stylesheet" media="all" href="' . $this->fileUrlGenerator
      ->generateString('core/modules/system/tests/modules/common_test/bar.css') . '?' . $query_string . '" />', $rendered_css, 'Rendering an external CSS file.');
    $this->assertStringContainsString('<script src="' . $this->fileUrlGenerator
      ->generateString('core/modules/system/tests/modules/common_test/foo.js') . '?' . $query_string . '"></script>', $rendered_js, 'Rendering an external JavaScript file.');
  }
  
  /**
   * Tests adding JavaScript settings.
   */
  public function testAddJsSettings() : void {
    // Add a file in order to test default settings.
    $build['#attached']['library'][] = 'core/drupalSettings';
    $assets = AttachedAssets::createFromRenderArray($build);
    $this->assertEquals([], $assets->getSettings(), 'JavaScript settings on $assets are empty.');
    $javascript = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $this->assertArrayHasKey('currentPath', $javascript['drupalSettings']['data']['path']);
    $this->assertArrayHasKey('currentPath', $assets->getSettings()['path']);
    $assets->setSettings([
      'drupal' => 'rocks',
      'dries' => 280342800,
    ]);
    $javascript = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $this->assertEquals(280342800, $javascript['drupalSettings']['data']['dries'], 'JavaScript setting is set correctly.');
    $this->assertEquals('rocks', $javascript['drupalSettings']['data']['drupal'], 'The other JavaScript setting is set correctly.');
  }
  
  /**
   * Tests adding external CSS and JavaScript files.
   */
  public function testAddExternalFiles() : void {
    $build['#attached']['library'][] = 'common_test/external';
    $assets = AttachedAssets::createFromRenderArray($build);
    $css = $this->assetResolver
      ->getCssAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage());
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $this->assertArrayHasKey('http://example.com/stylesheet.css', $css);
    $this->assertArrayHasKey('http://example.com/script.js', $js);
    $css_render_array = \Drupal::service('asset.css.collection_renderer')->render($css);
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_css = (string) $this->renderer
      ->renderInIsolation($css_render_array);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    $this->assertStringContainsString('<link rel="stylesheet" media="all" href="http://example.com/stylesheet.css" />', $rendered_css, 'Rendering an external CSS file.');
    $this->assertStringContainsString('<script src="http://example.com/script.js"></script>', $rendered_js, 'Rendering an external JavaScript file.');
  }
  
  /**
   * Tests adding JavaScript files with additional attributes.
   */
  public function testAttributes() : void {
    $build['#attached']['library'][] = 'common_test/js-attributes';
    $assets = AttachedAssets::createFromRenderArray($build);
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    $expected_1 = '<script src="http://example.com/deferred-external.js" foo="bar" defer></script>';
    $expected_2 = '<script src="' . $this->fileUrlGenerator
      ->generateString('core/modules/system/tests/modules/common_test/deferred-internal.js') . '?v=1" defer bar="foo"></script>';
    $this->assertStringContainsString($expected_1, $rendered_js, 'Rendered external JavaScript with correct defer and random attributes.');
    $this->assertStringContainsString($expected_2, $rendered_js, 'Rendered internal JavaScript with correct defer and random attributes.');
  }
  
  /**
   * Tests that attributes are maintained when JS aggregation is enabled.
   */
  public function testAggregatedAttributes() : void {
    $build['#attached']['library'][] = 'common_test/js-attributes';
    $assets = AttachedAssets::createFromRenderArray($build);
    $js = $this->assetResolver
      ->getJsAssets($assets, TRUE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    $expected_1 = '<script src="http://example.com/deferred-external.js" foo="bar" defer></script>';
    $expected_2 = '<script src="' . $this->fileUrlGenerator
      ->generateString('core/modules/system/tests/modules/common_test/deferred-internal.js') . '?v=1" defer bar="foo"></script>';
    $this->assertStringContainsString($expected_1, $rendered_js, 'Rendered external JavaScript with correct defer and random attributes.');
    $this->assertStringContainsString($expected_2, $rendered_js, 'Rendered internal JavaScript with correct defer and random attributes.');
  }
  
  /**
   * Integration test for CSS/JS aggregation.
   */
  public function testAggregation() : void {
    $build['#attached']['library'][] = 'core/drupal.timezone';
    $build['#attached']['library'][] = 'core/drupal.vertical-tabs';
    $assets = AttachedAssets::createFromRenderArray($build);
    $this->assertCount(1, $this->assetResolver
      ->getCssAssets($assets, TRUE, \Drupal::languageManager()->getCurrentLanguage()), 'There is a sole aggregated CSS asset.');
    [$header_js, $footer_js] = $this->assetResolver
      ->getJsAssets($assets, TRUE, \Drupal::languageManager()->getCurrentLanguage());
    $this->assertEquals([], \Drupal::service('asset.js.collection_renderer')->render($header_js), 'There are 0 JavaScript assets in the header.');
    $rendered_footer_js = \Drupal::service('asset.js.collection_renderer')->render($footer_js);
    $this->assertCount(3, $rendered_footer_js, 'There are 3 JavaScript assets in the footer.');
    $this->assertEquals('drupal-settings-json', $rendered_footer_js[0]['#attributes']['data-drupal-selector'], 'The first of the two JavaScript assets in the footer has drupal settings.');
    $this->assertStringContainsString('jquery.min.js', $rendered_footer_js[1]['#attributes']['src'], 'The second of the two JavaScript assets in the footer is jquery.min.js.');
    $this->assertStringStartsWith(base_path(), $rendered_footer_js[2]['#attributes']['src'], 'The third of the two JavaScript assets in the footer has the sole aggregated JavaScript asset.');
  }
  
  /**
   * Tests JavaScript settings.
   */
  public function testSettings() : void {
    $build = [];
    $build['#attached']['library'][] = 'core/drupalSettings';
    // Nonsensical value to verify if it's possible to override path settings.
    $build['#attached']['drupalSettings']['path']['pathPrefix'] = 'does_not_exist';
    $assets = AttachedAssets::createFromRenderArray($build);
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[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
      ->renderInIsolation($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('does_not_exist', $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']);
  }
  
  /**
   * Tests JS assets depending on the 'core/<head>' virtual library.
   */
  public function testHeaderHTML() : void {
    $build['#attached']['library'][] = 'common_test/js-header';
    $assets = AttachedAssets::createFromRenderArray($build);
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[0];
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    $query_string = $this->container
      ->get('asset.query_string')
      ->get();
    $this->assertStringContainsString('<script src="' . $this->fileUrlGenerator
      ->generateString('core/modules/system/tests/modules/common_test/header.js') . '?' . $query_string . '"></script>', $rendered_js, 'The JS asset in common_test/js-header appears in the header.');
    $this->assertStringContainsString('<script src="' . $this->fileUrlGenerator
      ->generateString('core/misc/drupal.js'), $rendered_js, 'The JS asset of the direct dependency (core/drupal) of common_test/js-header appears in the header.');
    $this->assertStringContainsString('<script src="' . $this->fileUrlGenerator
      ->generateString('core/misc/drupalSettingsLoader.js'), $rendered_js, 'The JS asset of the indirect dependency (core/drupalSettings) of common_test/js-header appears in the header.');
  }
  
  /**
   * Tests that for assets with cache = FALSE, Drupal sets preprocess = FALSE.
   */
  public function testNoCache() : void {
    $build['#attached']['library'][] = 'common_test/no-cache';
    $assets = AttachedAssets::createFromRenderArray($build);
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $this->assertFalse($js['core/modules/system/tests/modules/common_test/no_cache.js']['preprocess'], 'Setting cache to FALSE sets preprocess to FALSE when adding JavaScript.');
  }
  
  /**
   * Tests JavaScript versioning.
   */
  public function testVersionQueryString() : void {
    $build['#attached']['library'][] = 'core/once';
    $assets = AttachedAssets::createFromRenderArray($build);
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    $this->assertStringContainsString('core/assets/vendor/once/once.min.js?v=1.0.1', $rendered_js, 'JavaScript version identifiers correctly appended to URLs');
  }
  
  /**
   * Tests JavaScript and CSS asset ordering.
   */
  public function testRenderOrder() : void {
    $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, \Drupal::languageManager()->getCurrentLanguage())[1];
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    $matches = [];
    if (preg_match_all('/weight_([-0-9]+_[0-9]+)/', $rendered_js, $matches)) {
      $result = $matches[1];
    }
    else {
      $result = [];
    }
    $this->assertSame($expected_order_js, $result, '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, \Drupal::languageManager()->getCurrentLanguage());
    $css_render_array = \Drupal::service('asset.css.collection_renderer')->render($css);
    $rendered_css = (string) $this->renderer
      ->renderInIsolation($css_render_array);
    $matches = [];
    if (preg_match_all('/([a-z]+)_weight_([-0-9]+_[0-9]+)/', $rendered_css, $matches)) {
      $result = $matches[0];
    }
    else {
      $result = [];
    }
    $this->assertSame($expected_order_css, $result, 'CSS is added in the expected weight order.');
  }
  
  /**
   * Tests rendering the JavaScript with a file's weight above jQuery's.
   */
  public function testRenderDifferentWeight() : void {
    // If a library contains assets A and B, and A is listed first, then B can
    // still make itself appear first by defining a lower weight.
    $build['#attached']['library'][] = 'core/jquery';
    $build['#attached']['library'][] = 'common_test/weight';
    $assets = AttachedAssets::createFromRenderArray($build);
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    // Verify that lighter CSS assets are rendered first.
    $this->assertLessThan(strpos($rendered_js, 'first.js'), strpos($rendered_js, 'lighter.css'));
    // Verify that lighter JavaScript assets are rendered first.
    $this->assertLessThan(strpos($rendered_js, 'first.js'), strpos($rendered_js, 'lighter.js'));
    // Verify that a JavaScript file is rendered before jQuery.
    $this->assertLessThan(strpos($rendered_js, 'core/assets/vendor/jquery/jquery.min.js'), strpos($rendered_js, 'before-jquery.js'));
  }
  
  /**
   * Tests altering a JavaScript's weight via hook_js_alter().
   *
   * @see common_test_js_alter()
   */
  public function testAlter() : void {
    // Add both tableselect.js and alter.js.
    $build['#attached']['library'][] = 'core/drupal.tableselect';
    $build['#attached']['library'][] = 'common_test/hook_js_alter';
    $assets = AttachedAssets::createFromRenderArray($build);
    // Render the JavaScript, testing if alter.js was altered to be before
    // tableselect.js. See common_test_js_alter() to see where this alteration
    // takes place.
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    // Verify that JavaScript weight is correctly altered by the alter hook.
    $this->assertLessThan(strpos($rendered_js, 'core/misc/tableselect.js'), strpos($rendered_js, 'alter.js'));
  }
  
  /**
   * Adds a JavaScript library to the page and alters it.
   *
   * @see common_test_library_info_alter()
   */
  public function testLibraryAlter() : void {
    // Verify that common_test altered the title of loadjs.
    /** @var \Drupal\Core\Asset\LibraryDiscoveryInterface $library_discovery */
    $library_discovery = \Drupal::service('library.discovery');
    $library = $library_discovery->getLibraryByName('core', 'loadjs');
    $this->assertEquals('0.0', $library['version'], 'Registered libraries were altered.');
    // common_test_library_info_alter() also added a dependency on jQuery Form.
    $build['#attached']['library'][] = 'core/loadjs';
    $assets = AttachedAssets::createFromRenderArray($build);
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    $this->assertStringContainsString('core/misc/jquery.form.js', (string) $rendered_js, 'Altered library dependencies are added to the page.');
  }
  
  /**
   * Dynamically defines an asset library and alters it.
   */
  public function testDynamicLibrary() : void {
    /** @var \Drupal\Core\Asset\LibraryDiscoveryInterface $library_discovery */
    $library_discovery = \Drupal::service('library.discovery');
    // Retrieve a dynamic library definition.
    // @see common_test_library_info_build()
    \Drupal::state()->set('common_test.library_info_build_test', TRUE);
    $library_discovery->clear();
    $dynamic_library = $library_discovery->getLibraryByName('common_test', 'dynamic_library');
    $this->assertIsArray($dynamic_library);
    $this->assertArrayHasKey('version', $dynamic_library);
    $this->assertSame('1.0', $dynamic_library['version']);
    // Make sure the dynamic library definition could be altered.
    // @see common_test_library_info_alter()
    $this->assertArrayHasKey('dependencies', $dynamic_library);
    $this->assertSame([
      'core/jquery',
    ], $dynamic_library['dependencies']);
  }
  
  /**
   * Tests that multiple modules can implement libraries with the same name.
   *
   * @see common_test.library.yml
   */
  public function testLibraryNameConflicts() : void {
    /** @var \Drupal\Core\Asset\LibraryDiscoveryInterface $library_discovery */
    $library_discovery = \Drupal::service('library.discovery');
    $loadjs = $library_discovery->getLibraryByName('common_test', 'loadjs');
    $this->assertEquals('0.1', $loadjs['version'], 'Alternative libraries can be added to the page.');
  }
  
  /**
   * Tests JavaScript files that have query strings attached get added right.
   */
  public function testAddJsFileWithQueryString() : void {
    $build['#attached']['library'][] = 'common_test/querystring';
    $assets = AttachedAssets::createFromRenderArray($build);
    $css = $this->assetResolver
      ->getCssAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage());
    $js = $this->assetResolver
      ->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $this->assertArrayHasKey('core/modules/system/tests/modules/common_test/querystring.css?arg1=value1&arg2=value2', $css);
    $this->assertArrayHasKey('core/modules/system/tests/modules/common_test/querystring.js?arg1=value1&arg2=value2', $js);
    $css_render_array = \Drupal::service('asset.css.collection_renderer')->render($css);
    $rendered_css = (string) $this->renderer
      ->renderInIsolation($css_render_array);
    $js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
    $rendered_js = (string) $this->renderer
      ->renderInIsolation($js_render_array);
    $query_string = $this->container
      ->get('asset.query_string')
      ->get();
    $this->assertStringContainsString('<link rel="stylesheet" media="all" href="' . str_replace('&', '&amp;', $this->fileUrlGenerator
      ->generateString('core/modules/system/tests/modules/common_test/querystring.css?arg1=value1&arg2=value2')) . '&amp;' . $query_string . '" />', $rendered_css, 'CSS file with query string gets version query string correctly appended..');
    $this->assertStringContainsString('<script src="' . str_replace('&', '&amp;', $this->fileUrlGenerator
      ->generateString('core/modules/system/tests/modules/common_test/querystring.js?arg1=value1&arg2=value2')) . '&amp;' . $query_string . '"></script>', $rendered_js, 'JavaScript file with query string gets version query string correctly appended.');
  }
  
  /**
   * Test settings can be loaded even when libraries are not.
   */
  public function testAttachedSettingsWithoutLibraries() : void {
    $assets = new AttachedAssets();
    // First test with no libraries will return no settings.
    $assets->setSettings([
      'test' => 'foo',
    ]);
    $js = $this->assetResolver
      ->getJsAssets($assets, TRUE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $this->assertArrayNotHasKey('drupalSettings', $js);
    // Second test with a warm cache.
    $js = $this->assetResolver
      ->getJsAssets($assets, TRUE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $this->assertArrayNotHasKey('drupalSettings', $js);
    // Now test with different settings when drupalSettings is already loaded.
    $assets->setSettings([
      'test' => 'bar',
    ]);
    $assets->setAlreadyLoadedLibraries([
      'core/drupalSettings',
    ]);
    $js = $this->assetResolver
      ->getJsAssets($assets, TRUE, \Drupal::languageManager()->getCurrentLanguage())[1];
    $this->assertSame('bar', $js['drupalSettings']['data']['test']);
  }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
AssertContentTrait::$content protected property The current raw content.
AssertContentTrait::$drupalSettings protected property The drupalSettings value from the current raw $content.
AssertContentTrait::$elements protected property The XML structure parsed from the current raw $content.
AssertContentTrait::$plainTextContent protected property The plain-text content of raw $content (text nodes).
AssertContentTrait::assertEscaped protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertContentTrait::assertField protected function Asserts that a field exists with the given name or ID.
AssertContentTrait::assertFieldByName protected function Asserts that a field exists with the given name and value.
AssertContentTrait::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
AssertContentTrait::assertFieldsByValue protected function Asserts that a field exists in the current page with a given Xpath result.
AssertContentTrait::assertLink protected function Passes if a link with the specified label is found.
AssertContentTrait::assertLinkByHref protected function Passes if a link containing a given href (part) is found.
AssertContentTrait::assertNoLink protected function Passes if a link with the specified label is not found.
AssertContentTrait::assertNoPattern protected function Triggers a pass if the perl regex pattern is not found in raw content.
AssertContentTrait::assertNoRaw protected function Passes if the raw text is NOT found on the loaded page, fail otherwise.
AssertContentTrait::assertNoText protected function Passes if the page (with HTML stripped) does not contains the text.
AssertContentTrait::assertPattern protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertContentTrait::assertRaw protected function Passes if the raw text IS found on the loaded page, fail otherwise.
AssertContentTrait::assertText protected function Passes if the page (with HTML stripped) contains the text.
AssertContentTrait::assertTextHelper protected function Helper for assertText and assertNoText.
AssertContentTrait::assertThemeOutput protected function Asserts themed output.
AssertContentTrait::assertTitle protected function Pass if the page title is the given string.
AssertContentTrait::buildXPathQuery protected function Builds an XPath query.
AssertContentTrait::constructFieldXpath protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertContentTrait::cssSelect protected function Searches elements using a CSS selector in the raw content.
AssertContentTrait::getAllOptions protected function Get all option elements, including nested options, in a select.
AssertContentTrait::getDrupalSettings protected function Gets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::getRawContent protected function Gets the current raw content.
AssertContentTrait::getSelectedItem protected function Get the selected value from a select field.
AssertContentTrait::getTextContent protected function Retrieves the plain-text content from the current raw content.
AssertContentTrait::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
AssertContentTrait::removeWhiteSpace protected function Removes all white-space between HTML tags from the raw content.
AssertContentTrait::setDrupalSettings protected function Sets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::setRawContent protected function Sets the raw content (e.g. HTML).
AssertContentTrait::xpath protected function Performs an xpath search on the contents of the internal browser.
AttachedAssetsTest::$assetResolver protected property The asset resolver service.
AttachedAssetsTest::$fileUrlGenerator protected property The file URL generator.
AttachedAssetsTest::$modules protected static property Modules to install. Overrides KernelTestBase::$modules
AttachedAssetsTest::$renderer protected property The renderer service.
AttachedAssetsTest::setUp protected function Overrides KernelTestBase::setUp
AttachedAssetsTest::testAddExternalFiles public function Tests adding external CSS and JavaScript files.
AttachedAssetsTest::testAddFiles public function Tests adding a CSS and a JavaScript file.
AttachedAssetsTest::testAddJsFileWithQueryString public function Tests JavaScript files that have query strings attached get added right.
AttachedAssetsTest::testAddJsSettings public function Tests adding JavaScript settings.
AttachedAssetsTest::testAggregatedAttributes public function Tests that attributes are maintained when JS aggregation is enabled.
AttachedAssetsTest::testAggregation public function Integration test for CSS/JS aggregation.
AttachedAssetsTest::testAlter public function Tests altering a JavaScript&#039;s weight via hook_js_alter().
AttachedAssetsTest::testAttachedSettingsWithoutLibraries public function Test settings can be loaded even when libraries are not.
AttachedAssetsTest::testAttributes public function Tests adding JavaScript files with additional attributes.
AttachedAssetsTest::testDefault public function Tests that default CSS and JavaScript is empty.
AttachedAssetsTest::testDynamicLibrary public function Dynamically defines an asset library and alters it.
AttachedAssetsTest::testHeaderHTML public function Tests JS assets depending on the &#039;core/&lt;head&gt;&#039; virtual library.
AttachedAssetsTest::testLibraryAlter public function Adds a JavaScript library to the page and alters it.
AttachedAssetsTest::testLibraryNameConflicts public function Tests that multiple modules can implement libraries with the same name.
AttachedAssetsTest::testLibraryUnknown public function Tests non-existing libraries.
AttachedAssetsTest::testNoCache public function Tests that for assets with cache = FALSE, Drupal sets preprocess = FALSE.
AttachedAssetsTest::testRenderDifferentWeight public function Tests rendering the JavaScript with a file&#039;s weight above jQuery&#039;s.
AttachedAssetsTest::testRenderOrder public function Tests JavaScript and CSS asset ordering.
AttachedAssetsTest::testSettings public function Tests JavaScript settings.
AttachedAssetsTest::testVersionQueryString public function Tests JavaScript versioning.
BrowserHtmlDebugTrait::$htmlOutputBaseUrl protected property The Base URI to use for links to the output files.
BrowserHtmlDebugTrait::$htmlOutputClassName protected property Class name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounter protected property Counter for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounterStorage protected property Counter storage for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputDirectory protected property Directory name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputEnabled protected property HTML output enabled.
BrowserHtmlDebugTrait::$htmlOutputTestId protected property HTML output test ID.
BrowserHtmlDebugTrait::formatHtmlOutputHeaders protected function Formats HTTP headers as string for HTML output logging.
BrowserHtmlDebugTrait::getHtmlOutputHeaders protected function Returns headers in HTML output format. 1
BrowserHtmlDebugTrait::getResponseLogHandler protected function Provides a Guzzle middleware handler to log every response received.
BrowserHtmlDebugTrait::getTestMethodCaller protected function Retrieves the current calling line in the class under test. 1
BrowserHtmlDebugTrait::htmlOutput protected function Logs a HTML output message in a text file.
BrowserHtmlDebugTrait::initBrowserOutputFile protected function Creates the directory to store browser output.
ConfigTestTrait::configImporter protected function Returns a ConfigImporter object to import test configuration.
ConfigTestTrait::copyConfig protected function Copies configuration objects from source storage to target storage.
DrupalTestCaseTrait::$root protected property The Drupal root directory.
DrupalTestCaseTrait::checkErrorHandlerOnTearDown public function Checks the test error handler after test execution. 1
DrupalTestCaseTrait::getDrupalRoot protected static function Returns the Drupal root directory. 1
DrupalTestCaseTrait::setDebugDumpHandler public static function Registers the dumper CLI handler when the DebugDump extension is enabled.
ExtensionListTestTrait::getModulePath protected function Gets the path for the specified module.
ExtensionListTestTrait::getThemePath protected function Gets the path for the specified theme.
HttpKernelUiHelperTrait::$mink protected property Mink session manager.
HttpKernelUiHelperTrait::assertSession public function Returns WebAssert object.
HttpKernelUiHelperTrait::buildUrl protected function Builds a URL from a system path or a URL object.
HttpKernelUiHelperTrait::clickLink protected function Follows a link by complete name.
HttpKernelUiHelperTrait::drupalGet protected function Retrieves a Drupal path.
HttpKernelUiHelperTrait::getDefaultDriverInstance protected function Gets an instance of the default Mink driver.
HttpKernelUiHelperTrait::getNodeElementsByXpath protected function Performs an xpath search on the contents of the internal browser.
HttpKernelUiHelperTrait::getSession public function Returns Mink session.
HttpKernelUiHelperTrait::getUrl protected function Gets the current URL from the browser.
HttpKernelUiHelperTrait::initMink protected function Initializes Mink sessions.
KernelTestBase::$classLoader protected property The class loader.
KernelTestBase::$configImporter protected property The configuration importer.
KernelTestBase::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking. 4
KernelTestBase::$container protected property The test container.
KernelTestBase::$databasePrefix protected property The test database prefix.
KernelTestBase::$keyValue protected property The key_value service that must persist between container rebuilds.
KernelTestBase::$siteDirectory protected property The relative path to the test site directory.
KernelTestBase::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 9
KernelTestBase::$usesSuperUserAccessPolicy protected property Set to TRUE to make user 1 a super user. 1
KernelTestBase::$vfsRoot protected property The virtual filesystem root directory.
KernelTestBase::assertPostConditions protected function 1
KernelTestBase::bootEnvironment protected function Bootstraps a basic test environment.
KernelTestBase::bootKernel protected function Bootstraps a kernel for a test. 1
KernelTestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
KernelTestBase::disableModules protected function Disables modules for this test.
KernelTestBase::enableModules protected function Enables modules for this test. 2
KernelTestBase::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
KernelTestBase::getDatabaseConnectionInfo protected function Returns the Database connection info to be used for this test. 3
KernelTestBase::getDatabasePrefix public function Gets the database prefix used for test isolation.
KernelTestBase::getExtensionsForModules private function Returns Extension objects for $modules to install.
KernelTestBase::getModulesToEnable protected static function Returns the modules to install for this test.
KernelTestBase::initFileCache protected function Initializes the FileCache component.
KernelTestBase::installConfig protected function Installs default configuration for a given list of modules.
KernelTestBase::installEntitySchema protected function Installs the storage schema for a specific entity type.
KernelTestBase::installSchema protected function Installs database tables from a module schema definition.
KernelTestBase::register public function Registers test-specific services. Overrides ServiceProviderInterface::register 40
KernelTestBase::render protected function Renders a render array. 1
KernelTestBase::setInstallProfile protected function Sets the install profile and rebuilds the container to update it.
KernelTestBase::setSetting protected function Sets an in-memory Settings variable.
KernelTestBase::setUpFilesystem protected function Sets up the filesystem, so things like the file directory. 3
KernelTestBase::tearDown protected function 10
KernelTestBase::tearDownCloseDatabaseConnection public function Additional tear down method to close the connection at the end.
KernelTestBase::vfsDump protected function Dumps the current state of the virtual filesystem to STDOUT.
KernelTestBase::__sleep public function Prevents serializing any properties.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.