是否可以在同一个测试中使用 cy.intercept
多次拦截同一个 api 调用?我尝试了以下方法:
cy.intercept({ pathname: "/url", method: "POST" }).as("call1")
// ... some logic
cy.wait("@call1")
// ... some logic
cy.intercept({ pathname: "/url", method: "POST" }).as("call2")
// ... some logic
cy.wait("@call2")
我希望 cy.wait("@call2")
会等待 api 被调用的第二次。但是,秒 cy.wait
将立即继续,因为第一个 api 调用与第二个 api 调用相同。
答案 0 :(得分:4)
当您设置相同的拦截时,第一个将获取所有调用。但是您可以多次等待第一个别名。
这是一个(相当)简单的说明
规格
Cypress.config('defaultCommandTimeout', 10); // low timeout
// makes the gets depend on the waits
// for success
it('never fires @call2',()=>{
cy.intercept({ pathname: "/posts", method: "POST" }).as("call1")
cy.intercept({ pathname: "/posts", method: "POST" }).as("call2")
cy.visit('../app/intercept-identical.html')
cy.wait('@call1') // call1 fires
cy.get('div#1').should('have.text', '201')
cy.wait('@call2') // call2 never fires
cy.wait('@call1') // call1 fires a second time
cy.get('div#2').should('have.text', '201')
})
应用
<body>
<div id="1"></div>
<div id="2"></div>
<script>
setTimeout(() => {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }),
headers: { 'Content-type': 'application/json; charset=UTF-8' },
}).then(response => {
document.getElementById('1').innerText = response.status;
})
}, 500)
setTimeout(() => {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({ title: 'foo', body: 'bar', userId: 2 }),
headers: { 'Content-type': 'application/json; charset=UTF-8' },
}).then(response => {
document.getElementById('2').innerText = response.status;
})
}, 1000)
</script>
</body>
你可以在 Cypress 日志中看到它,
命令 | 调用# | 出现(橙色标签) |
---|---|---|
等待 | @call1 | 1 |
等待 | @call2 | |
等待 | @call1 | 2 |