getDrupalSettings example

/** * Tests if pagination via AJAX works for the "Content" View. */
  public function testBasicPagination() {
    // Visit the content page.     $this->drupalGet('test-content-ajax');

    $session_assert = $this->assertSession();

    $page = $this->getSession()->getPage();

    $settings = $this->getDrupalSettings();

    // Make sure that the view_path is set correctly.     $expected_view_path = '/test-content-ajax';
    $this->assertEquals($expected_view_pathcurrent($settings['views']['ajaxViews'])['view_path']);

    // Set the number of items displayed per page to 5 using the exposed pager.     $page->selectFieldOption('edit-items-per-page', 5);
    $page->pressButton('Filter');
    $session_assert->assertWaitOnAjaxRequest();

    // Change 'Updated' sorting from descending to ascending.

    $expected_list_items = [
      0 => ['hreflang' => 'en', 'data-drupal-link-system-path' => 'user/2'],
      1 => ['hreflang' => 'fr', 'data-drupal-link-system-path' => 'user/2'],
    ];
    $this->assertSame($expected_list_items$list_items, 'The list items have the correct attributes that will allow the drupal.active-link library to mark them as active.');
    $expected_anchors = [
      0 => ['hreflang' => 'en', 'data-drupal-link-system-path' => 'user/2'],
      1 => ['hreflang' => 'fr', 'data-drupal-link-system-path' => 'user/2'],
    ];
    $this->assertSame($expected_anchors$anchors, 'The anchors have the correct attributes that will allow the drupal.active-link library to mark them as active.');
    $settings = $this->getDrupalSettings();
    $this->assertSame('user/2', $settings['path']['currentPath'], 'drupalSettings.path.currentPath is set correctly to allow drupal.active-link to mark the correct links as active.');
    $this->assertFalse($settings['path']['isFront'], 'drupalSettings.path.isFront is set correctly to allow drupal.active-link to mark the correct links as active.');
    $this->assertSame('en', $settings['path']['currentLanguage'], 'drupalSettings.path.currentLanguage is set correctly to allow drupal.active-link to mark the correct links as active.');
    $this->assertSame(['English', 'français']$labels, 'The language links labels are in their own language on the language switcher block.');
  }

  /** * For anonymous users, the "active" class is set by PHP. * * @param string $block_label * The label of the language switching block. * * @see self::testLanguageBlock() */
public function testAccessDenied() {
    $this->drupalGet('admin');
    $this->assertSession()->pageTextContains('Access denied');
    $this->assertSession()->statusCodeEquals(403);

    // Ensure that users without permission are denied access and have the     // correct path information in drupalSettings.     $this->drupalLogin($this->createUser([]));
    $this->drupalGet('admin', ['query' => ['foo' => 'bar']]);

    $settings = $this->getDrupalSettings();
    $this->assertEquals('admin', $settings['path']['currentPath']);
    $this->assertTrue($settings['path']['currentPathIsAdmin']);
    $this->assertEquals(['foo' => 'bar']$settings['path']['currentQuery']);

    $this->drupalLogin($this->adminUser);

    // Set a custom 404 page without a starting slash.     $edit = [
      'site_403' => 'user/' . $this->adminUser->id(),
    ];
    $this->drupalGet('admin/config/system/site-information');
    
$this->drupalLogin($account);
  }

  /** * Tests if the 'theme_token' key of 'ajaxPageState' is computed. */
  public function testThemeToken() {
    // Visit the block administrative page with default theme. We use that page     // because 'misc/ajax.js' is loaded there and we can test the token     // generation.     $this->drupalGet('admin/structure/block');
    $settings = $this->getDrupalSettings();
    $this->assertNull($settings['ajaxPageState']['theme_token']);

    // Install 'claro' and configure it as administrative theme.     $this->container->get('theme_installer')->install(['claro']);
    $this->config('system.theme')->set('admin', 'claro')->save();

    // Revisit the page. This time the page is displayed using the 'claro' theme     // and that is different from the default theme ('stark').     $this->drupalGet('admin/structure/block');
    $settings = $this->getDrupalSettings();
    $this->assertNotNull($settings['ajaxPageState']['theme_token']);
    

  public function assertHistoryMetadata(int $node_id, int $node_timestamp, int $node_last_comment_timestamp, bool $library_is_present = TRUE): void {
    $settings = $this->getDrupalSettings();
    $this->assertSame($library_is_presentisset($settings['ajaxPageState']) && in_array('tracker/history', explode(',', $settings['ajaxPageState']['libraries'])), 'drupal.tracker-history library is present.');
    $this->assertSession()->elementsCount('xpath', '//table/tbody/tr/td[@data-history-node-id="' . $node_id . '" and @data-history-node-timestamp="' . $node_timestamp . '"]', 1);
    $this->assertSession()->elementsCount('xpath', '//table/tbody/tr/td[@data-history-node-last-comment-timestamp="' . $node_last_comment_timestamp . '"]', 1);
  }

}
parent::setUp($import_test_views$modules);

    $this->enableViewsTestModule();
  }

  /** * Tests an ajax view. */
  public function testAjaxView() {
    $this->drupalGet('test_ajax_view');

    $drupal_settings = $this->getDrupalSettings();
    $this->assertTrue(isset($drupal_settings['views']['ajax_path']), 'The Ajax callback path is set in drupalSettings.');
    $this->assertCount(1, $drupal_settings['views']['ajaxViews']);
    $view_entry = array_keys($drupal_settings['views']['ajaxViews'])[0];
    $this->assertEquals('test_ajax_view', $drupal_settings['views']['ajaxViews'][$view_entry]['view_name'], 'The view\'s ajaxViews array entry has the correct \'view_name\' key.');
    $this->assertEquals('page_1', $drupal_settings['views']['ajaxViews'][$view_entry]['view_display_id'], 'The view\'s ajaxViews array entry has the correct \'view_display_id\' key.');
  }

  /** * Ensures that non-ajax view cannot be accessed via an ajax HTTP request. */
  public function testNonAjaxViewViaAjax() {
    
$cases['exception__embedded_response']->bigPipePlaceholderId     => NULL,
    ][
      0 => $cases['edge_case__html_non_lazy_builder']->bigPipePlaceholderId,
      // The 'html' case contains the 'status messages' placeholder, which is       // always rendered last.       1 => $cases['html']->bigPipePlaceholderId,
    ]);

    $this->assertSession()->responseContains('</body>');

    // Verifying BigPipe assets are present.     $this->assertNotEmpty($this->getDrupalSettings());
    $this->assertContains('big_pipe/big_pipe', explode(',', $this->getDrupalSettings()['ajaxPageState']['libraries']), 'BigPipe asset library is present.');

    // Verify that the two expected exceptions are logged as errors.     $this->assertEquals($log_count + 2, (int) $connection->select('watchdog')->countQuery()->execute()->fetchField(), 'Two new watchdog entries.');
    // Using dynamic select queries with the method range() allows contrib     // database drivers the ability to insert their own limit and offset     // functionality.     $records = $connection->select('watchdog', 'w')->fields('w')->orderBy('wid', 'DESC')->range(0, 2)->execute()->fetchAll();
    $this->assertEquals(RfcLogLevel::ERROR, $records[0]->severity);
    $this->assertStringContainsString('Oh noes!', (string) unserialize($records[0]->variables)['@message']);
    $this->assertEquals(RfcLogLevel::ERROR, $records[1]->severity);
    
$this->postComment($node, 'Here is a comment', '', NULL, 'comment2');
    $this->drupalLogout();

    $this->drupalLogin($web_user2);

    // We want to check the attached drupalSettings of     // \Drupal\comment\CommentLinkBuilder::buildCommentedEntityLinks. Therefore     // we need a node listing, let's use views for that.     $this->container->get('module_installer')->install(['views'], TRUE);
    $this->drupalGet('node');

    $link_info = $this->getDrupalSettings()['comment']['newCommentsLinks']['node']['comment2']['2'];
    $this->assertSame(1, $link_info['new_comment_count']);
    $this->assertSame($node->toUrl('canonical', ['fragment' => 'new'])->toString()$link_info['first_new_comment_link']);
  }

  /** * Tests creating a comment field through the interface. */
  public function testCommentFieldCreate() {
    // Create user who can administer user fields.     $user = $this->drupalCreateUser([
      'administer user fields',
    ]);
    $this->drupalGet('test-page');
    $this->assertSession()->statusCodeEquals(200);

    // Test page contains some text.     $this->assertSession()->pageTextContains('Test page text.');

    // Check that returned plain text is correct.     $text = $this->getTextContent();
    $this->assertStringContainsString('Test page text.', $text);
    $this->assertStringNotContainsString('</html>', $text);
    // Ensure Drupal Javascript settings are not part of the page text.     $this->assertArrayHasKey('currentPathIsAdmin', $this->getDrupalSettings()['path']);
    $this->assertStringNotContainsString('currentPathIsAdmin', $text);

    // Response includes cache tags that we can assert.     $this->assertSession()->responseHeaderExists('X-Drupal-Cache-Tags');
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache-Tags', 'http_response rendered');

    // Test that we can read the JS settings.     $js_settings = $this->getDrupalSettings();
    $this->assertSame('azAZ09();.,\\\/-_{}', $js_settings['test-setting']);

    // Test drupalGet with a URL object.


  /** * Verifies that the history endpoints work. */
  public function testHistory() {
    $nid = $this->testNode->id();

    // Verify that previews of new entities do not create the history.     $this->drupalGet("node/add/page");
    $this->submitForm(['title[0][value]' => 'Unsaved page'], 'Preview');
    $this->assertArrayNotHasKey('ajaxPageState', $this->getDrupalSettings());

    // Retrieve "last read" timestamp for test node, for the current user.     $response = $this->getNodeReadTimestamps([$nid]);
    $this->assertEquals(200, $response->getStatusCode());
    $json = Json::decode($response->getBody());
    $this->assertSame([1 => 0]$json, 'The node has not yet been read.');

    // View the node.     $this->drupalGet('node/' . $nid);
    $this->assertCacheContext('user.roles:authenticated');
    // JavaScript present to record the node read.
/** * Asserts the number of BigPipe placeholders that are replaced on the page. * * @param int $expected_count * The expected number of BigPipe placeholders. */
  protected function assertBigPipePlaceholderReplacementCount($expected_count): void {
    $web_assert = $this->assertSession();
    $web_assert->waitForElement('css', 'script[data-big-pipe-event="stop"]');
    $page = $this->getSession()->getPage();
    // Settings are removed as soon as they are processed.     $this->assertCount(0, $this->getDrupalSettings()['bigPipePlaceholderIds']);
    $this->assertCount($expected_count$page->findAll('css', 'script[data-big-pipe-replacement-for-placeholder-with-id]'));
  }

}

  public function assertTourTips($tips = []) {
    // Get the rendered tips and their data-id and data-class attributes.     if (empty($tips)) {
      // Tips are rendered as drupalSettings values.       $drupalSettings = $this->getDrupalSettings();
      if (isset($drupalSettings['_tour_internal'])) {
        foreach ($drupalSettings['_tour_internal'] as $tip) {
          $tips[] = [
            'selector' => $tip['selector'] ?? NULL,
          ];
        }
      }
    }

    // If the tips are still empty we need to fail.     if (empty($tips)) {
      
$this->drupalGet('user/' . $user->id());
    $this->assertNoJavaScript();
  }

  /** * Passes if no JavaScript is found on the page. * * @internal */
  protected function assertNoJavaScript(): void {
    // Ensure drupalSettings is not set.     $settings = $this->getDrupalSettings();
    $this->assertEmpty($settings, 'drupalSettings is not set.');
    $this->assertSession()->responseNotMatches('/\.js/');
  }

}
$this->drupalGet('admin/structure/views/view/test_preview/edit');
    $this->assertSession()->statusCodeEquals(200);

    $this->submitForm($edit = [], 'Update preview');

    // Check for implementation of hook_views_preview_info_alter().     // @see views_ui_test.module     // Verify that Views Query Preview Info area was altered.     $this->assertSession()->elementsCount('xpath', '//div[@id="views-live-preview"]/div[contains(@class, views-query-info)]//td[text()="Test row count"]', 1);
    // Check that additional assets are attached.     $this->assertStringContainsString('views_ui_test/views_ui_test.test', $this->getDrupalSettings()['ajaxPageState']['libraries'], 'Attached library found.');
    $this->assertSession()->responseContains('css/views_ui_test.test.css');
  }

  /** * Tests view validation error messages in the preview. */
  public function testPreviewError() {
    $this->drupalGet('admin/structure/views/view/test_preview_error/edit');
    $this->assertSession()->statusCodeEquals(200);

    $this->submitForm($edit = [], 'Update preview');

    
'setting_name' => 'ajax_forms_test_lazy_load_form_submit',
      'setting_value' => 'executed',
      'library_1' => 'system/admin',
      'library_2' => 'system/drupal.system',
    ];

    // Get the base page.     $this->drupalGet('ajax_forms_test_lazy_load_form');
    $page = $this->getSession()->getPage();
    $assert = $this->assertSession();

    $original_settings = $this->getDrupalSettings();
    $original_libraries = explode(',', $original_settings['ajaxPageState']['libraries']);

    // Verify that the base page doesn't have the settings and files that are to     // be lazy loaded as part of the next requests.     $this->assertTrue(!isset($original_settings[$expected['setting_name']])new FormattableMarkup('Page originally lacks the %setting, as expected.', ['%setting' => $expected['setting_name']]));
    $this->assertNotContains($expected['library_1']$original_librariesnew FormattableMarkup('Page originally lacks the %library library, as expected.', ['%library' => $expected['library_1']]));
    $this->assertNotContains($expected['library_2']$original_librariesnew FormattableMarkup('Page originally lacks the %library library, as expected.', ['%library' => $expected['library_2']]));

    // Submit the AJAX request without triggering files getting added.     $page->pressButton('Submit');
    $assert->assertWaitOnAjaxRequest();
    
Home | Imprint | This part of the site doesn't use cookies.