Problem/Motivation

Test cases often need to check if the JavaScript settings on a returned page are correct. WebTestBase from SimpleTest had a method for that, we also want it on BrowserTestBase.

Proposed resolution

Implement the method getDrupalSettings() on BrowserTestBase.

Remaining tasks

Patch.

User interface changes

None.

API changes

None,

Data model changes

None.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

klausi created an issue. See original summary.

klausi’s picture

Status: Active » Needs review
FileSize
2.03 KB

Patch.

jibran’s picture

Status: Needs review » Reviewed & tested by the community

Nice and easy. Thanks @klausi

larowlan’s picture

Are we sure we want to go down this route? Shouldn't we be deferring all JavaScript functionality to JTB?
We deliberately avoided adding drupalPostAjaxForm to BTB for the same reason. If you want ajax, you use JTB instead of using poorman's emulation.

klausi’s picture

This is just for asserting that JS settings are on the page, it is not necessary to execute any js in the browser for that. I agree that any Ajax testing should be in JavascriptTestBase, but this check is fine here.

dawehner’s picture

Status: Reviewed & tested by the community » Needs work
+++ b/core/tests/Drupal/Tests/BrowserTestBase.php
@@ -1768,6 +1769,20 @@ protected function getUrl() {
   /**
+   * Gets the JavaScript drupalSettings variable for the currently-loaded page.
+   *
+   * @return array
+   *   The JSON decoded drupalSettings value from the current page.
+   */
+  protected function getDrupalSettings() {
+    $html = $this->getSession()->getPage()->getHtml();
+    if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $html, $matches)) {
+      return Json::decode($matches[1]);
+    }
+    return [];
+  }
+

Can we move this to the webassert?

klausi’s picture

Status: Needs work » Needs review

It is not an assertion method, so I think we should keep it on BrowserTestBase itself. Same as we have getUrl() or xpath() there.

dawehner’s picture

Status: Needs review » Reviewed & tested by the community

Ah you are right.

alexpott’s picture

Status: Reviewed & tested by the community » Fixed

Committed da9cb25 and pushed to 8.1.x and 8.2.x. Thanks!

  • alexpott committed 5356c84 on 8.2.x
    Issue #2759859 by klausi: Implement getDrupalSettings() on...

  • alexpott committed da9cb25 on 8.1.x
    Issue #2759859 by klausi: Implement getDrupalSettings() on...

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.