[英]Cypress 7.0+ / Override responses in intercept
我希望你一切都好。 我目前正在将 cypress 升级到 7.0。 (更准确地说是 v7.4.0)我有一个覆盖拦截调用的问题。
赛普拉斯团队似乎致力于解决最重要的问题https://github.com/cypress-io/cypress/pull/14543 (问题: https://github.com/cypress-io/cypress/issues/9302 ),但是它对我不起作用。
BREAKING CHANGE: Request handlers supplied to cy.intercept are now matched starting with the most-recently-defined request interceptor. This allows users to override request handlers by calling cy.intercept again. This matches the previous behavior that was standard in cy.route.
我的第一个电话处理 2xx 响应(我自己嘲笑它)
cy.intercept('GET', 'sameUrl', {
statusCode: 2xx
}
但后来我需要另一个截取相同的 url 但不同的状态:
cy.intercept('GET', 'sameUrl', {
statusCode: 4xx
}
我尝试使用middleware
: A new option, middleware, has been added to the RouteMatcher type. If true, the supplied request handler will be called before any non-middleware request handlers.
A new option, middleware, has been added to the RouteMatcher type. If true, the supplied request handler will be called before any non-middleware request handlers.
cy.intercept({ method: 'GET', url: 'sameUrl', middleware: true}, req => {
req.continue(res => {
res.statusCode = 4xx
});
}
但它没有用,第一个拦截总是被调用的那个。 请如果您知道我做错了什么/另一种解决方案,我全神贯注!
如果我制作一个最小的示例应用程序 + 测试,它会遵循您上面引用的规则。
测试
it('overrides the intercept stub', () => {
cy.visit('../app/intercept-override.html')
cy.intercept('GET', 'someUrl', { statusCode: 200 })
cy.get('button').click()
cy.get('div')
.invoke('text')
.should('eq', '200') // passes
cy.intercept('GET', 'someUrl', { statusCode: 404 })
cy.get('button').click()
cy.get('div')
.invoke('text')
.should('eq', '404') // passes
})
应用程序
<button onclick="clicked()">Click</button>
<div>Result</div>
<script>
function clicked() {
fetch('someUrl').then(response => {
const div = document.querySelector('div')
div.innerText = response.status
})
}
</script>
那么,你的应用有什么不同呢?
测试根据评论修改
打破测试的要点
**
才能工作beforeEach(() => {
cy.intercept('GET', /api\/test-id\/\d+/, { statusCode: 200 })
.as('myalias1')
cy.visit('../app/intercept-overide.html')
})
it('sees the intercept stub status 200', () => {
cy.get('button').click()
cy.wait('@myalias1')
cy.get('div')
.invoke('text')
.should('eq', '200')
})
it('sees the intercept stub status 404', () => {
cy.intercept('GET', '**/api/test-id/1', { statusCode: 404 })
.as('myalias2')
cy.get('button').click()
cy.wait('@myalias2')
cy.get('div')
.invoke('text')
.should('eq', '404')
})
应用程序
<button onclick="clicked()">Click</button>
<div>Result</div>
<script>
function clicked() {
fetch('/api/test-id/1').then(response => {
// logs as "http://localhost:53845/api/test-id/1" in the Cypress test runner
const div = document.querySelector('div')
div.innerText = response.status
})
}
</script>
迷你比赛
第二个拦截使用将使用 minimatch 匹配的字符串。 使用此代码检查拦截是否适用于您应用的 URL
Cypress.minimatch(<full-url-from-app>, <url-in-intercept>) // true if matching
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.