AssertBlockAppearsTrait.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace Drupal\Tests\block\Functional;
  3. use Drupal\block\Entity\Block;
  4. use Drupal\Component\Render\FormattableMarkup;
  5. /**
  6. * Provides test assertions for testing block appearance.
  7. *
  8. * Can be used by test classes that extend \Drupal\Tests\BrowserTestBase.
  9. */
  10. trait AssertBlockAppearsTrait {
  11. /**
  12. * Checks to see whether a block appears on the page.
  13. *
  14. * @param \Drupal\block\Entity\Block $block
  15. * The block entity to find on the page.
  16. */
  17. protected function assertBlockAppears(Block $block) {
  18. $result = $this->findBlockInstance($block);
  19. $this->assertTrue(!empty($result), new FormattableMarkup('The block @id appears on the page', ['@id' => $block->id()]));
  20. }
  21. /**
  22. * Checks to see whether a block does not appears on the page.
  23. *
  24. * @param \Drupal\block\Entity\Block $block
  25. * The block entity to find on the page.
  26. */
  27. protected function assertNoBlockAppears(Block $block) {
  28. $result = $this->findBlockInstance($block);
  29. $this->assertFalse(!empty($result), new FormattableMarkup('The block @id does not appear on the page', ['@id' => $block->id()]));
  30. }
  31. /**
  32. * Find a block instance on the page.
  33. *
  34. * @param \Drupal\block\Entity\Block $block
  35. * The block entity to find on the page.
  36. *
  37. * @return array
  38. * The result from the xpath query.
  39. */
  40. protected function findBlockInstance(Block $block) {
  41. return $this->xpath('//div[@id = :id]', [':id' => 'block-' . $block->id()]);
  42. }
  43. }