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

2022-08-06 00:00:00 javascript sitemap typescript 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;
};

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

相关文章