Request a specific comment

Imagine we have a page showing a number of a comment to fetch. The test needs to read the number from the page, then make a request to the API, and confirm the comment resource exists.

  Comment number <span data-cy="comment-number">#23#</span>
// first, find the element on the page
  // the text might have other characters which we will remove
  // the comment number must be an integer
  // thus we will remove all non-digit characters
  .invoke('replace', /[\D]/g, '')
  .should('be.a', 'number')
  .and('be.greaterThan', 0)
  .then((n) => {
    // cy.request automatically fails if the resource is missing
      .should('have.keys', [
      .then((comment) => {
          'fetched the right comment',
        )'id', n)
        // let's fetch the post for this comment
        cy.log(`fetching post **${comment.postId}**`)
          .should('have.keys', ['id', 'userId', 'body', 'title'])
        // we can fetch the user by id, or confirm something else

You can find this recipe explained in the video Request A Specific Comment Using Text From The Pageopen in new window