Skip to content

Feature Request Function to check HTML formatting in unit tests #1278

Description

@melissa-lynn

In the new unit tests for HTML active code, it would be helpful to add a function that checks for well-formatted HTML, in particular matching opening and closing tags. That way, if we're checking that a student has an h1 header, for example, we can avoid awarding full credit for a solution like the following (where the student makes an error in the closing tag).

<h1>hello<h1>

For consistency with the other test functions, I would think the test API would be something like:

assertValidHTML(msg)

AI suggested this could be implemented with the DOMParser API, with something like:

function isValidHTML(htmlString) {
  const parser = new DOMParser();
  // We wrap the snippet in a root element and parse as XML for strict validation
  const doc = parser.parseFromString('<root>${htmlString}</root>', 'application/xhtml+xml');
  
  const parserError = doc.querySelector('parsererror');
  
  if (parserError) {
    console.log("HTML Error found:", parserError.textContent);
    return false;
  }
  return true;
}

// Test cases
console.log(isValidHTML("<p>Hello <strong>World</strong></p>")); // true
console.log(isValidHTML("<p>Missing closing tag <span></p>"));   // false

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions