首页 > 解决方案 > 根据唯一测试提取站点地图 URL 和 cy.request() 每个 URL(赛普拉斯)

问题描述

使用 Cypress 和 TypeScript。

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

此版本有效:

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,因此数组已准备就绪。任何想法我做错了什么?

标签: javascripttypescriptcypresssitemap

解决方案


我的解决方案受到赛普拉斯示例回购的启发: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;
};

那么测试代码与上面链接的仓库中的方法相同。

在此处输入图像描述


推荐阅读