等到响应体在赛普拉斯中发生变化

时间:2020-07-28 18:37:41

标签: javascript api get xmlhttprequest cypress

我正在尝试使需要等待直到在响应正文中看到值成功的情况自动化。我尝试过的:

cy.server()
cy.route({
    method: 'GET',
    url: 'https://endpoint.com/api/readsomething'
    auth: {
        'username': username 
        'password': password
    },
    response: {}
}).as('checkStatus');

cy.wait('@checkStatus').then((ele) => {
expect(ele).should('have.property', 'response.body.latest_run.status', 'Success')
})
})

我收到以下错误消息:cy.wait() timed out waiting 5000ms for the 1st request to the route: checkStatus. No request ever occurred.

如果您能让我知道我在哪里做错,那将是很棒的事情。

2 个答案:

答案 0 :(得分:2)

通过查看请求cypress文档-https://docs.cypress.io/api/commands/request.html#Request-Polling

,我找到了解决方案

由于我要调用的API端点与我正在处理的应用程序不同,因此我使用cy.request()而不是cy.server() cy.route()

    function getStatus() {
        cy.request({
            method: 'GET',
            url: Cypress.config('endpoint'),
            auth: {
                'username': Cypress.config('username'),
                'password': Cypress.config('password')
            }
        }).then((response) => {
            if (response.body.status == "Success")
                return
            else
                getStatus()
        })
    }

    //Trigger the above function
    cy.then(getStatus)

答案 1 :(得分:1)

您需要触发UI操作。如果在页面加载时触发了API请求,则您需要执行cy.reload()cy.visit()或单击导航以使请求发生。如果这是由用户交互触发的。就像单击按钮一样,您需要通过cy.click()按钮或类似的东西来触发它。然后等待。

这是我们的project中的真实示例(简化了一点):

cy.server();
cy.route({
  method: 'GET',
  url: 'api/pipelines',
  response: mockedData,
}).as('getPipelines');

cy.reload(); // Reload the page and so we can wait for until `@getPipelines` request is resolve
cy.wait('@getPipelines');