Extract sitemap URLs and cy.request() each URL per a unique test (Cypress)

  cypress, javascript, sitemap, typescript

Using Cypress with TypeScript.

My code goal is to extract all URLs in /sitemap.xml and cy.request() each URL for status 200.

This version works:

describe('Sitemap Urls', () => {
  let urls: any[] = [];

  beforeEach(() => {
    cy.request({
      method: 'GET',
      url: 'https://docs.cypress.io/sitemap.xml',
    }).then(response => {
      expect(response.status).to.eq(200);

      urls = Cypress.$(response.body)
        .find('loc')
        .toArray()
        .map(el => el.textContent);

      cy.log('Array of Urls: ', urls);
    });
  });

  it(`Validate response of each URL in the sitemap`, () => {
      urls.forEach((uniqueUrl: any) => {
      cy.request(uniqueUrl).then(requestResponse => {
        expect(requestResponse.status).to.eq(200);
      });
    });
  });
});

But that runs every request in 1 test. I want each request to be it’s own test. But my code like this is not achieving this:

describe('Sitemap Urls', () => {
  let urls: any[] = ['/'];

  beforeEach(() => {
    cy.request({
      method: 'GET',
      url: 'https://docs.cypress.io/sitemap.xml',
    }).then(response => {
      expect(response.status).to.eq(200);

      urls = Cypress.$(response.body)
        .find('loc')
        .toArray()
        .map(el => el.textContent);

      cy.log('Array of Urls: ', urls);
    });
  });

  urls.forEach((uniqueUrl: any) => {
    it(`Validate response of each URL in the sitemap - ${uniqueUrl}`, () => {
      cy.request(uniqueUrl).then(requestResponse => {
        expect(requestResponse.status).to.eq(200);
      });
    });
  });
});

The debugger shows that urls.forEach() has populated all the URLs, so the array is ready. Any ideas what I’m doing wrong?

Source: Ask Javascript Questions

LEAVE A COMMENT