How to check for comments with cypress?

Viewed 227

Not the typical use case of using cypress, but I want to check for the existence of (certain) comments in the HTML code using cypress. What is the best way to do so?

1 Answers

To get comments like <!-- my-comment --> within <body>

function filterNone() {
  return NodeFilter.FILTER_ACCEPT;
}

function getAllComments(rootElem) {
  var comments = [];
  var iterator = document.createNodeIterator(rootElem, NodeFilter.SHOW_COMMENT, filterNone, false);
  var curNode;
  while (curNode = iterator.nextNode()) {
    comments.push(curNode.nodeValue);
  }
  return comments;
}

cy.get('body').then($body => {
  return cy.wrap(getAllComments($body[0]))
})
.should('deep.eq', [' my-comment '])

A more concise way

cy.document().then(doc => {

  const comments = [...doc.body.childNodes]
    .filter(node => node.nodeName === '#comment')
    .map(commentNode => commentNode.data) 

  cy.wrap(comments)
    .should('deep.eq', [' my-comment '])
})
Related