0

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?

Benny Meade
  • 602
  • 10
  • 25
  • Try for-of loop. It works for me for Javascript and I see there is such an option in Typescript. https://www.tutorialsteacher.com/typescript/for-loop Hope this helps – Rosen Mihaylov May 15 '21 at 16:27

1 Answers1

0

My solution was inspired by this Cypress examples repo: https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/fundamentals__dynamic-tests-from-api

Code for your /plugins.index.ts file:

const got = require('got');
const { parseString } = require('xml2js');

module.exports = async (on: any, config: any) => {
 await got('https://docs.cypress.io/sitemap.xml')
    .then((response: { body: any }) => {
      console.log('We got something');

      console.log(response.body);
      const sitemapUrls = [];

      parseString(response.body, function (err, result) {
        for (let url of result.urlset.url) {
          sitemapUrls.push(url.loc[0]);
        }
      });

      config.env.sitemapUrls = sitemapUrls;
    })
    .catch((error: any) => {
      console.log('We got nothing', error);
    });

  console.log(config.env.sitemapUrls);
  return config;
};

then the test code is same approach as in the repo linked above.

enter image description here

Benny Meade
  • 602
  • 10
  • 25