javascript - 根据唯一测试提取站点地图 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,因此数组已准备就绪。任何想法我做错了什么?
解决方案
我的解决方案受到赛普拉斯示例回购的启发: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;
};
那么测试代码与上面链接的仓库中的方法相同。
推荐阅读
- javascript - 如何使用 hyperledger Fabric 区块链应用程序修复“错误:14 不可用:TCP 写入失败”
- javascript - 使用 Autohotkey 运行书签
- javascript - 大于/小于符号不会被转义
- json - 如何在 SWIFT 中处理 JSON 中的空值
- ios - 无法为私有仓库添加带有 url 的源
- c++ - 关闭套接字如何影响对方读取
- asp.net - 是否可以扩展 IEntityHistoryStore 以存储每个表而不是在同一个表中跟踪所有内容?
- r - 如何获得所有变量的 woe(证据权重)值以及如何在 r 中应用逻辑回归模型?
- javascript - 数据绑定在哪里属于单页应用程序(JS 和 HTML)
- android - Intent -Android 后停止服务