evaluateScript example


  public function testDrupalSettingsCachingRegression() {
    $this->drupalGet('ajax-test/dialog');
    $assert = $this->assertSession();
    $session = $this->getSession();

    // Insert a fake library into the already loaded library settings.     $fake_library = 'fakeLibrary/fakeLibrary';
    $session->evaluateScript("drupalSettings.ajaxPageState.libraries = drupalSettings.ajaxPageState.libraries + ',$fake_library';");

    $libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
    // Test that the fake library is set.     $this->assertStringContainsString($fake_library$libraries);

    // Click on the AJAX link.     $this->clickLink('Link 8 (ajax)');
    $assert->assertWaitOnAjaxRequest();

    // Test that the fake library is still set after the AJAX call.     $libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
    
// The "Add Node" link triggers an off-canvas dialog with an add node form     // that includes CKEditor.     $page->clickLink('Add Node');
    $assert_session->waitForElementVisible('css', '#drupal-off-canvas-wrapper');
    $assert_session->assertWaitOnAjaxRequest();

    $styles = $assert_session->elementExists('css', 'style#ckeditor5-off-canvas-reset');
    $this->stringContains('#drupal-off-canvas-wrapper [data-drupal-ck-style-fence]', $styles->getText());

    $assert_session->elementExists('css', '.ck');

    $ckeditor_toolbar_bg_color = $this->getSession()->evaluateScript('window.getComputedStyle(document.querySelector(\'.ck.ck-toolbar\')).backgroundColor');
    $this->assertEquals('rgb(255, 255, 255)', $ckeditor_toolbar_bg_color, 'Toolbar background-color should be unaffected by off-canvas');
    // Editable area should be visible.     $assert_session->elementExists('css', '.ck .ck-content');
    $ckeditor_editable_bg_color = $this->getSession()->evaluateScript('window.getComputedStyle(document.querySelector(\'.ck.ck-content\')).backgroundColor');
    $this->assertEquals('rgb(255, 255, 255)', $ckeditor_editable_bg_color, 'Content background-color should be unaffected by off-canvas');
  }

}
$javascript = <<<JS (function(){ return window.performance .getEntries() .filter(function (entry) { return entry.initiatorType == 'fetch' && entry.name.indexOf('/media/test_format/preview') !== -1; }) .pop() .transferSize; })() JS;
    return $this->getSession()->evaluateScript($javascript);
  }

  /** * Ensure media preview isn't clickable. */
  public function testMediaPointerEvent() {
    $entityViewDisplay = EntityViewDisplay::load('media.image.view_mode_1');
    $thumbnail = $entityViewDisplay->getComponent('thumbnail');
    $thumbnail['settings']['image_link'] = 'file';
    $entityViewDisplay->setComponent('thumbnail', $thumbnail);
    $entityViewDisplay->save();

    

  protected $defaultTheme = 'stark';

  /** * Tests AjaxFocusFirstCommand on a page. */
  public function testFocusFirst() {
    $page = $this->getSession()->getPage();
    $assert_session = $this->assertSession();

    $this->drupalGet('ajax-test/focus-first');
    $has_focus_id = $this->getSession()->evaluateScript('document.activeElement.id');
    $this->assertNotContains($has_focus_id['edit-first-input', 'edit-first-container-input']);

    // Confirm that focus does not change if the selector targets a     // non-focusable container containing no tabbable elements.     $page->pressButton('SelectorNothingTabbable');
    $this->assertNotNull($assert_session->waitForElementVisible('css', '#edit-selector-has-nothing-tabbable[data-has-focus]'));
    $has_focus_id = $this->getSession()->evaluateScript('document.activeElement.id');
    $this->assertEquals('edit-selector-has-nothing-tabbable', $has_focus_id);

    // Confirm that focus does not change if the page has no match for the     // provided selector.
$this->assertNotEmpty($iframe_url['query']);
    $query = [];
    parse_str($iframe_url['query']$query);
    $this->assertSame($video_url$query['url']);
    $this->assertNotEmpty($query['hash']);
    // Ensure that the outer iframe's width respects the formatter settings.     $this->assertSame('240', $iframe->getAttribute('width'));
    // Check the inner iframe to make sure that CSS has been applied to scale it     // correctly, regardless of whatever its width attribute may be (the fixture     // hard-codes it to 480).     $inner_frame = 'frames[0].document.querySelector("iframe")';
    $this->assertSame('480', $session->evaluateScript("$inner_frame.getAttribute('width')"));
    $this->assertLessThanOrEqual(240, $session->evaluateScript("$inner_frame.clientWidth"));

    // The oEmbed content iFrame should be visible.     $assert_session->elementExists('css', 'iframe.media-oembed-content');
    // The thumbnail should not be displayed.     $assert_session->elementNotExists('css', 'img');

    // Load the media and check that all fields are properly populated.     $media = Media::load(1);
    $this->assertSame('Drupal Rap Video - Schipulcon09', $media->getName());
    $this->assertSame('480', $media->field_string_width->value);
    
$xpath", d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, r = n.getBoundingClientRect(), lx = (w.innerWidth || e.clientWidth), ly = (w.innerHeight || e.clientHeight); return t(r, lx, ly); }($test_javascript_function)); JS;

    // Check the visibility by injecting and executing the full JavaScript test     // script in the page.     return $this->session->evaluateScript($full_javascript_visibility_test);
  }

  /** * Passes if the raw text IS NOT found escaped on the loaded page. * * Raw text refers to the raw HTML that the page generated. * * @param string $raw * Raw (HTML) string to look for. */
  public function assertNoEscaped($raw) {
    
$this->clickContextualLink('#block-branding', 'Test Link with Ajax', FALSE);
    $this->assertNotEmpty($this->assertSession()->waitForElementVisible('css', '#drupal-modal'));
    $this->assertSession()->elementContains('css', '#drupal-modal', 'Everything is contextual!');
    $this->getSession()->executeScript('document.querySelector("#block-branding .trigger").addEventListener("focus", (e) => e.target.classList.add("i-am-focused"))');
    $this->getSession()->getPage()->pressButton('Close');
    $this->assertSession()->assertNoElementAfterWait('css', 'ui.dialog');

    // When the dialog is closed, the opening contextual link is now inside a     // collapsed container, so focus should be routed to the contextual link     // toggle button.     $this->assertNotNull($this->assertSession()->waitForElement('css', '.trigger.i-am-focused')$this->getSession()->getPage()->find('css', '#block-branding')->getOuterHtml());
    $this->assertJsCondition('document.activeElement === document.querySelector("#block-branding button.trigger")', 10000, 'Focus should be on the contextual trigger, but instead is at ' . $this->getSession()->evaluateScript('document.activeElement.outerHTML'));

    // Check to make sure that page was not reloaded.     $this->assertSession()->pageTextContains($current_page_string);

    // Test clicking contextual link with toolbar.     $this->container->get('module_installer')->install(['toolbar']);
    $this->grantPermissions(Role::load(Role::AUTHENTICATED_ID)['access toolbar']);
    $this->drupalGet('user');
    $this->assertSession()->assertWaitOnAjaxRequest();

    // Click "Edit" in toolbar to show contextual links.
      // still on-going.       $result = $this->getSession()->wait(5000, '(typeof(jQuery)=="undefined" || (0 === jQuery.active && 0 === jQuery(\':animated\').length))');
      if (!$result) {
        // If the wait is unsuccessful, there may still be an AJAX request in         // progress. If we tear down now, then this AJAX request may fail with         // missing database tables, because tear down will have removed them.         // Rather than allow it to fail, throw an explicit exception now         // explaining what the problem is.         throw new \RuntimeException('Unfinished AJAX requests while tearing down a test');
      }

      $warnings = $this->getSession()->evaluateScript("JSON.parse(sessionStorage.getItem('js_testing_log_test.warnings') || JSON.stringify([]))");
      foreach ($warnings as $warning) {
        if (str_starts_with($warning, '[Deprecation]')) {
          @trigger_error('Javascript Deprecation:' . substr($warning, 13), E_USER_DEPRECATED);
        }
      }
    }
    parent::tearDown();
  }

  /** * Triggers a test failure if a JavaScript error was encountered. * * @throws \PHPUnit\Framework\AssertionFailedError * * @postCondition */
    $this->drupalGet($form_path);
    $page->pressButton("AJAX changed: Click to mark div changed with asterisk.");
    $this->assertWaitPageContains('<div id="changed_div" class="ajax-changed"> <div id="changed_div_mark_this">This div can be marked as changed or not. <abbr class="ajax-changed" title="Changed">*</abbr> </div></div>');

    // Tests the 'css' command.     $page->pressButton("Set the '#box' div to be blue.");
    $this->assertWaitPageContains('<div id="css_div" style="background-color: blue;">');

    // Tests the 'data' command.     $page->pressButton("AJAX data command: Issue command.");
    $this->assertTrue($page->waitFor(10, function D) use ($session) {
      return 'testvalue' === $session->evaluateScript('window.jQuery("#data_div").data("testkey")');
    }));

    // Tests the 'html' command.     $page->pressButton("AJAX html: Replace the HTML in a selector.");
    $this->assertWaitPageContains('<div id="html_div">replacement text</div>');

    // Tests the 'insert' command.     $page->pressButton("AJAX insert: Let client insert based on #ajax['method'].");
    $this->assertWaitPageContains('<div id="insert_div">insert replacement textOriginal contents</div>');

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

    // Dynamically change the setting using JavaScript.     $script = <<<EndOfScript (function () { drupalSettings['test-setting'] = 'foo'; })(); EndOfScript;

    $this->getSession()->evaluateScript($script);

    // Check that the setting has been changed.     $js_settings = $this->getDrupalSettings();
    $this->assertSame('foo', $js_settings['test-setting']);
  }

}

  protected function getElementVerticalPosition($css_selector$position_type) {
    $this->assertContains($position_type['top', 'bottom'], 'Expected position type.');
    return (int) $this->getSession()->evaluateScript("document.querySelector('$css_selector').getBoundingClientRect().$position_type + window.pageYOffset");
  }

  /** * Moves mouse pointer to location of $selector. * * @param string $selector * CSS selector. */
  protected function movePointerTo($selector) {
    $driver_session = $this->getSession()->getDriver()->getWebDriverSession();
    $element = $driver_session->element('css selector', $selector);
    
// Now that there definitely is no more AJAX request in progress, count the     // number of AJAX responses.     $javascript = <<<JS (function(){ return window.performance .getEntries() .filter(entry => entry.initiatorType === 'xmlhttprequest' && entry.name.indexOf('_wrapper_format=drupal_ajax') !== -1) .length })() JS;
    return $this->getSession()->evaluateScript($javascript);
  }

  /** * CKEditor 5's filter UI modifications should not break it for other editors. */
  public function testUnavailableFiltersHiddenWhenSwitching() {
    $page = $this->getSession()->getPage();
    $assert_session = $this->assertSession();
    $this->createNewTextFormat($page$assert_session, 'unicorn');
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->pageTextNotContains('Filter settings');

    
// Expected state values with the user tray open with horizontal     // orientation.     $expected = [
      'orientation' => 'horizontal',
      'hasActiveTab' => TRUE,
      'activeTabId' => 'toolbar-item-user',
      'activeTray' => 'toolbar-item-user-tray',
      'isOriented' => TRUE,
      'isFixed' => TRUE,
    ];
    $toolbar_stored_state = JSON::decode(
      $this->getSession()->evaluateScript("sessionStorage.getItem('Drupal.toolbar.toolbarState')")
    );

    // The userButtonMinWidth property will differ depending on the length of     // the test-generated username, so it is checked differently and the value     // is copied to the expected value array.     $this->assertNotNull($toolbar_stored_state['userButtonMinWidth']);
    $this->assertIsNumeric($toolbar_stored_state['userButtonMinWidth']);
    $this->assertGreaterThan(60, $toolbar_stored_state['userButtonMinWidth']);
    $expected['userButtonMinWidth'] = $toolbar_stored_state['userButtonMinWidth'];

    $this->assertSame($expected$toolbar_stored_state);

    
    $body = '';
    for ($i = 0; $i < 10; $i++) {
      $body .= '<p>' . $this->randomMachineName(32) . '</p>';
    }
    $edit_url = $this->drupalCreateNode(['type' => 'article', 'body' => ['value' => $body, 'format' => 'test_format']])->toUrl('edit-form');
    $this->drupalGet($edit_url);
    $this->assertNotEmpty($assert_session->waitForElement('css', '#toolbar-bar'));
    $this->assertNotEmpty($assert_session->waitForElement('css', '.ck-editor'));

    // Ensure the body has enough height to enable scrolling. Scroll 110px from     // top of body field to ensure CKEditor 5 toolbar is sticky.     $this->getSession()->evaluateScript('document.body.style.height = "10000px";');
    $this->getSession()->evaluateScript('location.hash = "#edit-body-0-value";');
    $this->getSession()->evaluateScript('scroll(0, document.documentElement.scrollTop + 110);');
    // Focus CKEditor 5 text editor.     $javascript = <<<JS Drupal.CKEditor5Instances.get(document.getElementById("edit-body-0-value").dataset["ckeditor5Id"]).editing.view.focus(); JS;
    $this->getSession()->evaluateScript($javascript);

    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-sticky-panel__placeholder'));
    $toolbar_height = (int) $this->getSession()->evaluateScript('document.getElementById("toolbar-bar").offsetHeight');
    $ckeditor5_toolbar_position = (int) $this->getSession()->evaluateScript("document.querySelector('.ck-toolbar').getBoundingClientRect().top");
    
$this->clickLink('Add block');
    $assert_session->assertWaitOnAjaxRequest();

    // Get all blocks, for assertions later.     $blocks = $page->findAll('css', '.js-layout-builder-categories li');
    $categories = $page->findAll('css', '.js-layout-builder-category');

    $filter = $assert_session->elementExists('css', '.js-layout-builder-filter');

    // Set announce to ensure it is not cleared.     $init_message = 'init message';
    $session->evaluateScript("Drupal.announce('$init_message')");
    // Test block filter does not take effect for 1 character.     $filter->setValue('a');
    $this->assertAnnounceContains($init_message);
    $visible_rows = $this->filterVisibleElements($blocks);
    $this->assertSameSize($blocks$visible_rows);

    // Get the Content Fields category, which will be closed before filtering.     $contentFieldsCategory = $page->find('named', ['content', 'Content fields']);
    // Link that belongs to the Content Fields category, to verify collapse.     $promoteToFrontPageLink = $page->find('named', ['content', 'Promoted to front page']);
    // Test that front page link is visible until Content Fields collapsed.
Home | Imprint | This part of the site doesn't use cookies.