2 回答

TA貢獻1864條經(jīng)驗 獲得超6個贊
通常有人建議使用Promise.all,這不是正確的解決方案。Cypress chainer 對象與Promises/A+ 不兼容,它們看起來只是 Promise,因為它們實現(xiàn)了.then接口。這就是為什么Promise.all能夠使用一系列鏈接器對象的原因,僅此而已。傳遞給Promise.all().then回調(diào)的分辨率值不會是您所期望的(請參閱https://github.com/cypress-io/cypress/issues/915)。
您可以使用我在類似答案中建議的助手:
// put this in cypress/support/index.js
const chainStart = Symbol();
cy.all = function ( ...commands ) {
const _ = Cypress._;
const chain = cy.wrap(null, { log: false });
const stopCommand = _.find( cy.queue.commands, {
attributes: { chainerId: chain.chainerId }
});
const startCommand = _.find( cy.queue.commands, {
attributes: { chainerId: commands[0].chainerId }
});
const p = chain.then(() => {
return _( commands )
.map( cmd => {
return cmd[chainStart]
? cmd[chainStart].attributes
: _.find( cy.queue.commands, {
attributes: { chainerId: cmd.chainerId }
}).attributes;
})
.concat(stopCommand.attributes)
.slice(1)
.flatMap( cmd => {
return cmd.prev.get('subject');
})
.value();
});
p[chainStart] = startCommand;
return p;
}
用法:
it('test', () => {
const urls = [
'https://en.wikipediaaa.org',
'https://en.wikipedia.org'
];
cy.all(
...urls.map(url => cy.request(url))
).then(responses => {
responses.forEach( resp => {
expect(resp.status).to.eq(200);
});
});
});
話雖如此,你也可以這樣做:
const urls = [
'https://en.wikipediaaa.org',
'https://en.wikipedia.org'
];
let passes = 0;
urls.forEach( url => {
cy.request(url).then( resp => {
if ( resp.status === 200 ) passes++;
});
});
cy.then(() => {
expect(passes).to.eq(urls.length);
});
cy.all如果您想訪問結(jié)果而不必保留全局變量并從cy.then()回調(diào)中訪問它們,那么頂部的助手非常有用——但就像我在上一個示例中所示,一切都可以使用香草柏樹解決。
或者,如果您根本不需要響應(yīng),您可以簡單地執(zhí)行以下操作:
const urls = [
'https://en.wikipediaaa.org',
'https://en.wikipedia.org'
];
urls.forEach( url => {
cy.request(url).its('status').should('eq', 200);
});

TA貢獻1865條經(jīng)驗 獲得超7個贊
可以從 cy.requests 收集多個結(jié)果嗎?
您可以將它們?nèi)渴占饋?,并在Cypress.Promise.all僅在所有響應(yīng)準(zhǔn)備就緒時采取行動
it.only('Gathering results', () => {
const urls = ['https://google.com',
'https://en.wikipedia.org']
const requests = urls.map(url => {
console.log(`a request sent to ${url}`)
return new Cypress.Promise(resolve => {
cy.request(url).then(resopnse => {
console.log(`'Response from ${url}`)
resolve(resopnse)
})
})
})
Cypress.Promise.all(requests).then(responses => {
// process responses
console.log("All responses ready")
console.log(responses.map(response => response.redirects.toString()))
})
})
我們應(yīng)該使用 Cypress 來檢查外部站點的狀態(tài)嗎?
我沒有你在做什么的完整背景。顯然,您似乎正在使用 Cypress 作為監(jiān)控工具,定期檢查某些外部站點的可用性并發(fā)送通知。如果是這樣,我會說不,Cypress 是一個測試框架,用于編寫您自己的服務(wù)/系統(tǒng)的測試。
添加回答
舉報