Gather the URLs from the sitemap and use cy.request() to test each individual URL in Cypress

Using TypeScript with Cypress for URL extraction.

I have a code objective to extract and validate all URLs in the /sitemap.xml file using cy.request() to check for a status of 200.

The initial version successfully achieves 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);
    });
  });

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

However, I'd like each request to be its own separate test rather than grouped together in one. My attempt at modifying the code doesn't produce the desired outcome:

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);
   });
 });
});
});

Even though the debugger confirms that urls.forEach() has populated all the URLs in the array, the test cases are not executing individually as intended. Any suggestions on what might be causing this issue?

Answer №1

I found my solution through the insightful examples provided in this Cypress repository: https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/fundamentals__dynamic-tests-from-api

Here's a snippet of code to be added to 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('Insightful response received');

      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('No useful response received', error);
    });

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

The testing methodology aligns with that demonstrated in the previously mentioned repository.

https://i.sstatic.net/cEOQO.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`How can TypeScript scripts be incorporated with Electron?`

As I work on my simple electron app, I am facing an issue where I need to include a script using the following code: <script src="build/script.js"></script> In my project, I have a script.ts file that compiles to the build folder. im ...

Having trouble logging in with Google using React, Redux, and Typescript - encountered an error when attempting to sign in

As a beginner in TS, Redux, and React, I am attempting to incorporate Google Auth into my project. The code seems functional, but upon trying to login, an error appears in the console stating "Login failed." What adjustments should be made to resolve thi ...

a tutorial on linking component data to a prop value

Is there a way to connect the searchString value in my Vue component to the item value in the html template it uses? I need to pass this value to the method called in my Ajax request. Vue: Vue.component('user-container-component', { props: ...

checkbox with an option tag

I need help with implementing multi-select checkboxes inside an Angular 4 application. The checkboxes are not appearing next to the team names as intended. Can anyone assist me with this issue? Below is a snippet of my HTML code: <select class="form-c ...

Running Functions Out of Order in JavaScript - An exploration of Asynchronous Execution

I've been working on understanding how to manage the execution order of my script using asynchronous functions and promises. Despite going through numerous resources, I'm still struggling with getting it to work as expected: My approach involves ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...

Combine multiple form values to calculate the total sum

To tackle the issue of adding up independent totals in a PHP foreach loop and displaying a grand total, we need to modify the JavaScript function. Right now, the function works fine for each line, but doesn't calculate the grand total correctly. Let&a ...

Dynamically change the content of the DataTable by utilizing jQuery

I am facing an issue with updating a DataTable using jQuery when the contents of the table are modified. Initially, I have a HTML table with an empty tbody, which is populated dynamically based on selected filters such as select options. The table uses Dat ...

What is the best way to confirm checkbox selection based on MySQL data?

Writing this question feels challenging, but I have a collection of checkboxes with their data stored as JSON in my PHP database. What I'm trying to achieve now is to dynamically load the JSON data on the page without refreshing it, checking specific ...

Tips for extracting value from PHP and transferring it to a jQuery function

I am trying to calculate the distance between two airports and pass this value back to a jQuery function to use it in further calculations. I'm unsure of where I went wrong? HTML: The 'dept' and 'dest' inputs fetch airport informa ...

Issue with Empty Date Time Format in Vue2 Date-Picker

In our company, we use vue2-datepicker to manage the starting and ending times of meetings. The dates are stored in "YYYY-MM-DD HH:mm" format on the backend, but we convert them to "DD-MM-YYYY HH:mm" format when retrieving the data in the mounted() hook. T ...

What is preventing jQuery from converting this HTML string into a jQuery object?

I am struggling with converting a template string into a jQuery object in order to parse it and populate the data. $(function(){ var template = '<h3>Details</h3>' + '<ul>' + '<li>Submitted: <sp ...

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...

Navigating and retrieving information from JSON data

I'm working with JSON data that I have received: [{"pk": 7, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "6count1%2", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:01", "dish": 6, ...

Connect an input in VueJS to a VueX store state value

As someone new to VueJS, I'm currently working on a VueJS application that provides information about a Github user. For example, you can check out details for . I've set up a store using VueX, but I'm facing an issue with updating the valu ...

What is the best way to calculate the average of values from multiple objects sharing the same key in an array using JavaScript?

Consider an array with student profiles: let profile = [ {student: "A", english: 80, maths: 80}, {student: "A", english: 70, maths: 60}, {student: "B", english: 50, maths: 50}, {student: "B", english: "--", ...

Exploring the history object in the latest version of React Router (v4)

Despite trying various suggested solutions from different discussions, I am still unable to get it to work, which is why I am reaching out for help. This is how my history.js looks: import { createBrowserHistory } from 'history'; export defaul ...

JSON geometry imported is not following the movement of the bones

After importing a model into my Three.js scene, I encountered an issue where the bones can be moved and rotated successfully, but the model's geometry does not follow these bone movements. For importing the JSON file and adding it to the scene, here ...

Exploring the Crossroads of JSP and External Javascript Documents

I am new to using external JavaScript files (*.js). I have my JSP file ready, but my manager wants me to incorporate graphics into it. After searching, I found some *.js files. However, I am unsure of how to connect them with my JSP page. I need a way to ...