Cypress 测试 - 不拦截 api 请求

标签 cypress cypress-intercept

我需要测试项目上的一些页面,该项目对外部服务进行一些 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 调用。

来自Network Requests docs

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/

相关文章:

javascript - 如何使用.then() 之外的.then() 内设置的var 值?

javascript - 无法覆盖 Cypress 拦截

testing - 点击 Cypress 中的元素后自动调用 API

cypress - 如何让 cypress 等待依赖于另一个响应的响应?

vue.js - 如何使用 v-model 测试带有 cypress (10.x) 的 vue 3 组件

javascript - Cypress 测试在使用 invoke () 文本方法时抛出无法识别的表达式

javascript - 如何触发外部点击事件?

javascript - CYPRESS:检查按钮是否被禁用的函数