使用 Cypress Intercept 来模拟路由,我想验证路由被调用的次数。到目前为止,我在文档中没有找到任何相关内容。其中有提到cy.spy但每次只返回 1。有一个{times:N}用于拦截路由的对象,但它允许路由匹配并成功任意次。它不起到呼叫限制的作用。这是一个如此普遍的需求,我确信我只是错过了一些东西,眼睛疲劳等等。
间谍:
cy.intercept({method: 'GET', url:'my-url', middleware:cy.spy().as('myspy')})
Run Code Online (Sandbox Code Playgroud)
次数:
cy.intercept({method: 'GET', url:'my-url'}, {times:0})
Run Code Online (Sandbox Code Playgroud)
小智 11
柏树拦截的是间谍。
问题是何时检查呼叫计数。
例如,http://cypress.io/page-data
it('counts intercepts', () => {
let requestCounter = 0;
let responseCounter = 0;
cy.intercept('page-data/**/*', (req) => {
requestCounter += 1; // count requests
req.on('response', () => responseCounter += 1 ) // or count responses
})
cy.visit('https://www.cypress.io/')
cy.wait(5000).then(() => { // arbitrary wait
expect(requestCounter).to.eq(18) // since we don't know exactly
expect(responseCounter).to.eq(18) // what loads last
})
})
Run Code Online (Sandbox Code Playgroud)
Jennifer Shehane 在链接的功能请求中给出的答案显示了另一种使用方式<alias>.all,
it('counts intercepts', () => {
cy.intercept('page-data/**/*')
.as('pageData')
cy.visit('https://www.cypress.io/')
cy.get('@pageData.all')
.should('have.length', 18);
})
Run Code Online (Sandbox Code Playgroud)
然而,它并没有始终如一地通过。我的机器上大约有五分之一的运行会失败,因为 cy.get() 响应太早。
理想情况下,您应该能够添加超时,但这目前没有效果。
cy.get('@pageData.all', { timeout: 10000 }) // does not observe the timeout
Run Code Online (Sandbox Code Playgroud)
用作cy.spy()routeHandler 允许在检查调用计数的代码上设置超时。
it('counts intercepts', () => {
cy.intercept({ url: 'page-data/**/*', middleware: true }, req => {
req.on('response', (res) => {
res.setDelay(2000) // artificial delay to force failure
})
})
const spy = cy.spy();
cy.intercept('page-data/**/*', spy)
cy.visit('https://www.cypress.io/')
cy.wrap({}, { timeout: 10000 }) // adjust timeout to suit worst case page load
.should(() => {
console.log('testing spy') // see the retry happening (90+ logs)
expect(spy).to.be.callCount(18)
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9546 次 |
| 最近记录: |