如何在Cypress中等待IBM Watson服务的长耗时响应?
解决Cypress等待长耗时Watson接口的问题
你的核心问题是拦截定义时机错误,且未给cy.wait设置足够的超时时间,另外后续弹窗操作的代码也存在语法问题,下面一步步修正:
1. 提前定义接口拦截
cy.intercept必须放在触发请求的操作(点击[data-cy="testing"]按钮)之前,这样Cypress才能监听并捕获到目标请求。你原来把拦截放在点击之后,还错误用waitUntil包裹,完全没必要。
2. 给cy.wait设置超时时间
Watson接口耗时超过Cypress默认的5000ms,直接在cy.wait里通过timeout参数指定更长的超时(比如40000ms)即可覆盖默认限制。
3. 修正弹窗操作的语法错误
原代码中cy.window().its('open').should('exist').get('[data-cy="continuar]').click()是错误的——cy.window().its('open')获取的是浏览器的window.open方法,和页面内的弹窗元素无关。应该直接等待弹窗里的目标按钮可见后再点击。
修改后的完整测试代码
describe("E2E CognitiveTool", function() { it("should crear respuesta simple sin problemas", function() { cy.visit("http://localhost:3000"); cy.contains('[data-cy="topicName"]', 'CA2'); cy.get('[data-cy="accederResponsesCA2"]').click(); cy.get('[data-cy="crearResponse"]').should('exist').click(); cy.get('input[name="description"]').type('Simple Cypres Response'); cy.get('[name="typeResponse"]').first().check({force:true}); cy.get('[name="lateral_W"]').first().check({force:true}); cy.get('[name="rolViews"]').first().check({force:true}); cy.get('[name="workLoadLevel"]').first().check({force:true}); cy.get('[data-cy="continuar"]').click(); cy.get('input[id=0]').type('hola'); cy.get('input[id=1]').type('adios'); cy.get('input[id=2]').type('cypress'); cy.get('input[id=3]').type('jest'); cy.get('input[id=4]').type('testing'); cy.get('input[id=5]').type('automatico'); // 提前定义接口拦截,放在触发请求的点击操作之前 cy.intercept('POST', '**/test-watson').as('testData'); // 触发请求 cy.get('[data-cy="testing"]').should('exist').click({force: true}); // 等待接口响应,设置40秒超时 cy.wait('@testData', { timeout: 40000 }); // 等待弹窗中的按钮可见并点击 cy.get('[data-cy="continuar"]', { timeout: 10000 }).should('be.visible').click(); }); });
额外说明
- 如果弹窗是新开的浏览器窗口,需要用
cy.window()配合cy.stub()监听window.open,再切换到新窗口操作;但从你的描述看应该是页面内弹窗,直接等待元素即可。 - 可以额外验证接口状态码,确保请求成功:
cy.wait('@testData').its('response.statusCode').should('eq', 200)
内容的提问来源于stack exchange,提问作者ddaudiosolutions
相关产品推荐
相关产品推荐

