Skip to content

Instantly share code, notes, and snippets.

@WengerK
Last active March 27, 2024 10:38
Show Gist options
  • Save WengerK/90c52dc0d45c927aae995fb533f8066f to your computer and use it in GitHub Desktop.
Save WengerK/90c52dc0d45c927aae995fb533f8066f to your computer and use it in GitHub Desktop.
Debug Drupal - KernelTest, BrowserTest & JavascriptTest

Debug Drupal - KernelTest, BrowserTest & JavascriptTest

Debugging tests can often be a pain, but using those snippets it's possible to get a lot of informations when using BrowserTestBase or JavascriptTestBase.

Get HTML of a page

Sometimes you'll want to inspect the HTML of the page or a specific element. There is no official method for this yet but the following works:

$this->assertEquals('', $this->getSession()->getPage()->getHTML());

Your test will now fail with the HTML in the assert error message.

Sometimes, the HTMl page is way too heavy to be printed on the console. You can then just print it to a file

file_put_contents('/PATH/TO/test.html', $this->getSession()->getPage()->getHTML());

Don't put the screenshot in a path inside the test environment like public://test.html as this will be cleaned up at the end of the test.

$this->createScreenshot(\Drupal::root() . '/sites/default/files/simpletest/test.html');

Get Screenshot of a page (JavascriptTestBase)

If you want to see a screenshot to work out what is going on you can do this! (introduced in 8.1.9)

$this->createScreenshot('PATH/TO/screenshot.png');

Don't put the screenshot in a path inside the test environment like public://test.jpg as this will be cleaned up at the end of the test.

$this->createScreenshot(\Drupal::root() . '/sites/default/files/simpletest/screen.png');

Debugging Javascript (JavascriptTestBase)

If your test is having a strange problem, you can add a line like this just before the failure, which will basically stop the test in Chrome and let you play with the test site and look around:

$this->assertSession()->waitForElementVisible('css', '.test-wait', 100000000000000000000000000);
@JPustkuchen
Copy link

Very very helpful, @WengerK! :)
Thank you!

Just found a Gist with further helpful Drupal testing snippets:
https://gist.github.com/joshsedl/083064e4ec8f5f7cdf0c0d74d423850f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment