cypress dont find any test - tests on urls from sitemaps

Viewed 45

hello

I am trying to read online xml sitemap , and test each url that appear there. I need every url in a different 'it' section, so it wouldn't fail the rest of the test if one of the url fail.I guess because the urls from an online xml file its make the error. Because when i tried it on a different array of urls worked. any solutions?:)

describe('betting-guides', () => {
    // // initialize the url array
    let urls = []
    
    before(async () => {
      // getch the sitemap content
      const response = await cy.request('XMLFileName.xml')
  
      // convert sitemap xml body to an array of urls
      urls = Cypress.$(response.body)

        .find('loc')
        // map to a js array
        .toArray()
        // get the text of the <loc /> node
        .map(el => el.innerText)

    })

   it('' , ()=> {
    urls.forEach((url) => {
     // it('should succesfully load each url in the sitemap in ' + url, ()=> {
        cy.pargraphHasMoreThan100words(url)
    //  })
    })
  })
1 Answers

You can't generate tests using Cypress commands, in this recipe the comment explains it

/// <reference types="cypress" />
describe('generated from fixture', () => {
  // We cannot load JSON file using "cy.fixture"
  // because it means the test is already running.
  // Same with using "before" hook - new tests cannot be created from "before" hook.
  // Instead we need to load JSON file using "require" at the start time
  // and generate tests.
  const colors = require('../fixtures/colors')
  const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'violet']

  colors.forEach((color) => {
    it(` has color ${color}`, () => {
      cy.wrap(color).should('be.oneOf', rainbow)
    })
  })
})

The trick used here is to require() a file and generate the tests from it's content.

You can create the fixture of urls in the experimental before:run hook,

cypress/plugins/index.js

/// <reference types="cypress" />

const fs = require('fs-extra')
const https = require('https')
const flow = require('xml-flow')

module.exports = (on, config) => {

  on('before:run', () => {

    const file = fs.createWriteStream('cypress/fixtures/sitemap.xml');

    https.get('https://example.com/sitemap.xml', function(res) {
      res.on('data', function(data) {
        file.write(data);
      }).on('end', function() {
        file.end();
        const inFile = fs.createReadStream('cypress/fixtures/sitemap.xml')
        const xmlStream = flow(inFile);
          const urls = [];
          xmlStream.on('tag:loc', function(url) {
            urls.push(url.$text);
          });
          xmlStream.on('end', function() {
            fs.writeJsonSync('cypress/fixtures/urls.json', { urls })
          })
      })
    })
  })

  return config
}

Installs

yarn add -D fs-extra xml-flow

cypress.json

{
  "experimentalInteractiveRunEvents": true
}
Related