愿所有的美好和期待都能如约而至

提取站点地图URL,并对每个URL执行唯一的测试 Cypress

发布时间:  来源:互联网  作者:匿名  标签:cypress error Extract sitemap URLs and cy.request() each URL per a unique test (  热度:37.5℃

本文介绍了提取站点地图URL,并对每个URL执行唯一的测试(Cypress)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将Cypress与打字稿一起使用。

我的代码目标是提取/sitemap.xml中的所有URL,并提取状态为200的每个URL的cy.request()。

此版本有效:

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

但这会在1个测试中运行每个请求。我希望每个请求都是它自己的测试。但我的代码并没有实现这一点:

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

调试器显示urls.forEach()已经填充了所有URL,因此数组已经准备好了。你知道我做错了什么吗?

推荐答案

我的解决方案灵感来自于这个柏树示例Repo:https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/fundamentals__dynamic-tests-from-api

您的/plugins.index.ts文件的代码:

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

则测试代码与上面链接的回购中的方法相同。

这篇关于提取站点地图URL,并对每个URL执行唯一的测试(Cypress)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,

勇敢去编程!

勇敢的热爱编程,未来的你一定会大放异彩,未来的生活一定会因编程更好!

TOP