diff --git a/core/modules/help_topics/tests/src/Kernel/HelpTopicCoreTopicsTest.php b/core/modules/help_topics/tests/src/Kernel/HelpTopicCoreTopicsTest.php
index 6ca6eb4929..4ad4579323 100644
--- a/core/modules/help_topics/tests/src/Kernel/HelpTopicCoreTopicsTest.php
+++ b/core/modules/help_topics/tests/src/Kernel/HelpTopicCoreTopicsTest.php
@@ -149,16 +149,29 @@ protected function verifyTopic($id) {
$text = preg_replace('|\s+|', '', $text);
$this->assertTrue(empty($text), 'Topic ' . $id . ' Twig file contains only translated text');
- // Verify that there is not an H1 tag.
- $this->assertTrue(strpos($body, '
assertTrue($has_heading[$num - 1] || !$has_heading[$num],
- 'Topic ' . $id . ' has the correct H2-H6 heading hierarchy');
+ // Load the topic body as HTML and verify that it parses.
+ $doc = new \DOMDocument();
+ $doc->strictErrorChecking = TRUE;
+ $doc->validateOnParse = TRUE;
+ $doc->loadHTML($body);
+
+ // Check for headings hierarchy.
+ $levels = [1, 2, 3, 4, 5, 6];
+ foreach ($levels as $level) {
+ $num_headings[$level] = $doc->getElementsByTagName('h' . $level)->length;
+ if ($level == 1) {
+ $this->assertTrue($num_headings[1] == 0, 'Topic ' . $id . ' has no H1 tag');
+ // Set num_headings to 1 for this level, so the rest of the hierarchy
+ // can be tested using simpler code.
+ $num_headings[1] = 1;
+ }
+ else {
+ // We should either not have this heading, or if we do have one at this
+ // level, we should also have the next-smaller level. That is, if we
+ // have an h3, we should have also had an h2.
+ $this->assertTrue($num_headings[$level - 1] > 0 || $num_headings[$level] == 0,
+ 'Topic ' . $id . ' has the correct H2-H6 heading hierarchy');
+ }
}
}