assertJsCondition example

$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.
$machine_name_1_value = $page->find('css', '#edit-machine-name-1-label-machine-name-suffix .machine-name-value');
    $machine_name_2_value = $page->find('css', '#edit-machine-name-2-label-machine-name-suffix .machine-name-value');
    $machine_name_3_value = $page->find('css', '#edit-machine-name-3-label-machine-name-suffix .machine-name-value');
    $button_1 = $page->find('css', '#edit-machine-name-1-label-machine-name-suffix button.link');

    // Assert all fields are initialized correctly.     $this->assertNotEmpty($machine_name_1_value, 'Machine name field 1 must be initialized');
    $this->assertNotEmpty($machine_name_2_value, 'Machine name field 2 must be initialized');
    $this->assertNotEmpty($machine_name_3_value, 'Machine name field 3 must be initialized');

    // Assert that a machine name based on a default value is initialized.     $this->assertJsCondition('jQuery("#edit-machine-name-3-label-machine-name-suffix .machine-name-value").html() == "yet_another_machine_name"');

    // Field must be present for the rest of the test to work.     if (empty($machine_name_1_value)) {
      $this->fail('Cannot finish test, missing machine name field');
    }

    // Test each value for conversion to a machine name.     foreach ($test_values as $test_info) {
      // Set the value for the field, triggering the machine name update.       $title_1->setValue($test_info['input']);

      

  protected function waitUntilVisible($selector$timeout = 1000, $message = '') {
    $condition = "jQuery('" . $selector . ":visible').length > 0";
    $this->assertJsCondition($condition$timeout$message);
  }

  /** * Asserts that a link to a new media item is displayed in the messages area. * * @return string * The link URL. */
  protected function assertLinkToCreatedMedia() {
    $assert_session = $this->assertSession();
    $selector = 'div[aria-label="Status message"] a';

    
$time_diff = $page->find('css', ".entity-$delta")->getText();
      $regex_pattern = "#{$row['pattern']}#";
      // Test that the correct time difference is displayed. Note that we are       // able to check an exact match for rows that have a creation date more       // distant, but we use regexp to check the entities that are only few       // seconds away because of the latency introduced by the test run.       $this->assertMatchesRegularExpression($regex_pattern$time_diff);
    }

    // Wait at least 1 second + 1 millisecond to make sure the 'right now' time     // difference was refreshed.     $this->assertJsCondition("document.querySelector('.entity-$delta time').textContent >= '$time_diff'", 1001);
  }

  /** * Provides data for view rows. * * @return array[] * A list of row data. */
  protected function getRowData(): array {
    $now = \Drupal::time()->getRequestTime();
    return [
      

      ],
    ])->save();

    $this->drupalLogin($this->drupalCreateUser(['administer filters']));
    $this->drupalGet('admin/config/content/formats/manage/some_html');

    $js_condition = "Drupal.behaviors.filterFilterHtmlUpdating._parseSetting( jQuery('#edit-filters-filter-html-settings-allowed-html').val() )['td'].tags.length >= 0";

    $this->assertJsCondition($js_condition);
  }

}
public function testModalRenderer() {
    $session_assert = $this->assertSession();
    $this->drupalGet('/dialog_renderer-test-links');
    $this->clickLink('Normal Modal!');

    // Neither of the wide modals should have been used.     $style = $session_assert->waitForElementVisible('css', '.ui-dialog')->getAttribute('style');
    $this->assertStringNotContainsString('700px', $style);
    $this->assertStringNotContainsString('1000px', $style);

    // Tabbable should focus the close button when it is the only tabbable item.     $this->assertJsCondition('document.activeElement === document.querySelector(".ui-dialog .ui-dialog-titlebar-close")');
    $this->drupalGet('/dialog_renderer-test-links');
    $this->clickLink('Wide Modal!');
    $this->assertNotEmpty($session_assert->waitForElementVisible('css', '.ui-dialog[style*="width: 700px;"]'));
    $this->drupalGet('/dialog_renderer-test-links');
    $this->clickLink('Extra Wide Modal!');
    $this->assertNotEmpty($session_assert->waitForElementVisible('css', '.ui-dialog[style*="width: 1000px;"]'));

    $this->drupalGet('/dialog_renderer-test-links');
    $this->clickLink('Hidden close button modal!');
    $session_assert->waitForElementVisible('css', '.ui-dialog');

    
'access content',
      'access contextual links',
      'administer nodes',
      'administer blocks',
      'administer views',
      'edit any page content',
    ]));
    // Ensure same contextual links work correct with fresh and cached page.     foreach (['fresh', 'cached'] as $state) {
      $this->drupalGet('user');
      $contextual_id = '[data-contextual-id^="node:node=1"]';
      $this->assertJsCondition("(typeof jQuery !== 'undefined' && jQuery('[data-contextual-id]:empty').length === 0)");
      $this->getSession()->executeScript("jQuery('#block-first $contextual_id .trigger').trigger('click');");
      $contextual_links = $this->assertSession()->waitForElementVisible('css', "#block-first $contextual_id .contextual-links");
      $this->assertTrue($contextual_links->isVisible(), "Contextual links are visible with $state page.");
    }
  }

}
/** * Asserts a media item was added, but not yet saved. * * @param int $index * (optional) The index of the media item, if multiple items can be added at * once. Defaults to 0. */
  protected function assertMediaAdded($index = 0) {
    $selector = '.js-media-library-add-form-added-media';

    // Assert that focus is shifted to the new media items.     $this->assertJsCondition('jQuery("' . $selector . '").is(":focus")');

    $assert_session = $this->assertSession();
    $assert_session->pageTextMatches('/The media items? ha(s|ve) been created but ha(s|ve) not yet been saved. Fill in any required fields and save to add (it|them) to the media library./');
    $assert_session->elementAttributeContains('css', $selector, 'aria-label', 'Added media items');

    $fields = $this->assertElementExistsAfterWait('css', '[data-drupal-selector="edit-media-' . $index . '-fields"]');
    $assert_session->elementNotExists('css', '.js-media-library-menu');

    // Assert extraneous components were removed in     // FileUploadForm::hideExtraSourceFieldComponents().     $assert_session->elementNotExists('css', '[data-drupal-selector$="preview"]', $fields);
    
$this->drupalLogin($this->drupalCreateUser());
    $this->drupalGet(Url::fromRoute('big_pipe_regression_test.2678662'));

    // Confirm that AJAX behaviors were instantiated, if not, this points to a     // JavaScript syntax error.     $javascript = <<<JS (function(){ return Object.keys(Drupal.ajax.instances).length > 0; }()) JS;
    $this->assertJsCondition($javascript);

    // Besides verifying there is no JavaScript syntax error, also verify the     // HTML structure.     // The BigPipe stop signal is present just before the closing </body> and     // </html> tags.     $this->assertSession()
      ->responseContains(BigPipe::STOP_SIGNAL . "\n\n\n</body></html>");
    $js_code_until_closing_body_tag = substr(BigPipeRegressionTestController::MARKER_2678662, 0, strpos(BigPipeRegressionTestController::MARKER_2678662, '</body>'));
    // The BigPipe start signal does NOT start at the closing </body> tag string     // in an inline script.     $this->assertSession()
      
$javascript = <<<JS (function(){ var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w.innerHeight || e.clientHeight|| g.clientHeight; return x == 400 && y == 300; }()) JS;
    $this->assertJsCondition($javascript);

    // Ensure that \Drupal\Tests\UiHelperTrait::isTestUsingGuzzleClient() works     // as expected.     $this->assertFalse($this->isTestUsingGuzzleClient());
  }

  public function testAssertJsCondition() {
    $this->drupalGet('<front>');
    $session = $this->getSession();

    $session->resizeWindow(500, 300);
    
    $this->assertSession()->pageTextNotContains('You have unsaved changes.');

    // Drag and drop the '1st page' row over the '2nd page' row.     // @todo Test also the reverse, '2nd page' over '1st page', when     // https://www.drupal.org/node/2769825 is fixed.     // @see https://www.drupal.org/node/2769825     $dragged = $this->xpath("//tr[@data-drupal-selector='edit-table-book-admin-{$page1->id()}']//a[@class='tabledrag-handle']")[0];
    $target = $this->xpath("//tr[@data-drupal-selector='edit-table-book-admin-{$page2->id()}']//a[@class='tabledrag-handle']")[0];
    $dragged->dragTo($target);

    // Give javascript some time to manipulate the DOM.     $this->assertJsCondition('jQuery(".tabledrag-changed-warning").is(":visible")');

    // Check that the 'unsaved changes' text appeared in the message area.     $this->assertSession()->pageTextContains('You have unsaved changes.');

    // Check that '2nd page' page precedes the '1st page'.     $this->assertOrderInPage(['2nd page', '1st page']);

    $this->submitForm([], 'Save book pages');
    $this->assertSession()->pageTextContains(new FormattableMarkup('Updated book @book.', ['@book' => $book->getTitle()]));

    // Check that page reordering was done in the backend for drag-n-drop.
$page = $this->getSession()->getPage();

      $page->findLink('Edit view name/description')->click();
      $this->getSession()->executeScript("document.title = 'Initial title | " . \Drupal::config('system.site')->get('name') . "'");

      $admin_name_field = $this->assertSession()
        ->waitForField('Administrative name');
      $dialog_buttons = $page->find('css', '.ui-dialog-buttonset');
      $admin_name_field->setValue($new_title);

      $dialog_buttons->pressButton('Apply');
      $this->assertJsCondition("document.title === '" . $new_title . " (Content) | " . \Drupal::config('system.site')->get('name') . "'");
    }
  }

  /** * Tests contextual links on Views page displays. */
  public function testPageContextualLinks() {
    $view = View::load('test_display');
    $view->enable()->save();
    $this->container->get('router.builder')->rebuildIfNeeded();

    
$this->drupalGet('admin/structure/media');
    $assert_session->pageTextContains('No media types available. Add media type.');
    $assert_session->linkExists('Add media type');

    // Test the creation of a media type using the UI.     $name = $this->randomMachineName();
    $description = $this->randomMachineName();
    $this->drupalGet('admin/structure/media/add');
    $page->fillField('label', $name);
    $machine_name = strtolower($name);
    $this->assertJsCondition("jQuery('.machine-name-value').html() == '$machine_name'");
    $page->selectFieldOption('source', 'test');
    $this->assertJsCondition("jQuery('.form-item-source-configuration-test-config-value').length > 0");
    $page->fillField('description', $description);
    $page->pressButton('Save');
    // The wait prevents intermittent test failures.     $result = $assert_session->waitForLink('Add media type');
    $this->assertNotEmpty($result);
    $assert_session->addressEquals('admin/structure/media');
    $assert_session->pageTextContains('The media type ' . $name . ' has been added.');
    $this->drupalGet('admin/structure/media');
    $assert_session->pageTextContains($name);
    
$this->mediaItems['Horse'],
        $this->mediaItems['Bear'],
      ],
    ]);
    $this->drupalGet($node->toUrl('edit-form'));
    $open_button = $this->assertElementExistsAfterWait('css', '.js-media-library-open-button[name^="field_twin_media"]');
    // The open button should be disabled, but not have the     // 'data-disabled-focus' attribute.     $this->assertFalse($open_button->hasAttribute('data-disabled-focus'));
    $this->assertTrue($open_button->hasAttribute('disabled'));
    // The button should be disabled.     $this->assertJsCondition('jQuery("#field_twin_media-media-library-wrapper .js-media-library-open-button").is(":disabled")');
    // The button should not have focus.     $this->assertJsCondition('jQuery("#field_twin_media-media-library-wrapper .js-media-library-open-button").not(":focus")');
  }

  /** * Tests that the Media library's widget works as expected. */
  public function testWidget() {
    $assert_session = $this->assertSession();
    $page = $this->getSession()->getPage();

    
// Switch to manual mode.     $weight_toggle->click();
    $field_region = $page->findField('fields[field_test][region]');

    // Change the region to content using the region field.     $this->assertEquals('hidden', $field_region->getValue());
    $field_region->setValue('content');
    $assert_session->assertWaitOnAjaxRequest();

    // Confirm the region element retains focus after the AJAX update completes.     $this->assertJsCondition('document.activeElement === document.querySelector("[name=\'fields[field_test][region]\']")');
    $button_save->click();

    // Change the format for the test field.     $field_test_format_type->setValue('field_test_multiple');
    $assert_session->assertWaitOnAjaxRequest();

    // Confirm the format element retains focus after the AJAX update completes.     $this->assertJsCondition('document.activeElement === document.querySelector("[name=\'fields[field_test][type]\']")');

    $plugin_summary = $page->find('css', '#field-test .field-plugin-summary');
    $this->assertStringContainsString("test_formatter_setting_multiple: dummy test string", $plugin_summary->getText(), 'The expected summary is displayed.');

    
Home | Imprint | This part of the site doesn't use cookies.