我需要测试项目上的一些页面,该项目对外部服务进行一些 API 调用。
我需要确保进行这些调用,并检查我的页面是否根据响应而更改。
这是我的测试:
describe('A logged in user', () =>{
it('can see his subscriptions', () => {
...... some checks .......
cy.intercept('https://example.com/api/v2/user-panel/get-subscription').as('userSubscription');
cy.wait('@userSubscription', { timeout: 35000 }).then(() => {
cy.contains('some text');
});
});
});
当我运行代码时,它似乎无法调用 API,但页面内容会正确更改。
这是柏树的回应:
Timed out retrying after 35000ms: cy.wait() timed out waiting 35000ms for the 1st request to the route: userSubscription. No request ever occurred.
我尝试增加超时事件,如果页面在 1 秒内加载,但结果是相同的。
我缺少什么吗?
最佳答案
在 cy.intercept()
之后执行 cy.wait()
是行不通的。
无论什么触发 API 调用(cy.visit()
或 .click()
),都必须发生在之后 拦截已设置,因此已准备好捕获 API 调用。
cy.intercept('/activities/*', { fixture: 'activities' }).as('getActivities')
cy.intercept('/messages/*', { fixture: 'messages' }).as('getMessages')
// visit the dashboard, which should make requests that match
// the two routes above
cy.visit('http://localhost:8888/dashboard')
// pass an array of Route Aliases that forces Cypress to wait
// until it sees a response for each request that matches
// each of these aliases
cy.wait(['@getActivities', '@getMessages'])
// these commands will not run until the wait command resolves above
cy.get('h1').should('contain', 'Dashboard')
关于Cypress 测试 - 不拦截 api 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71867397/