如何在运行Cypress测试时等待AJAX请求完成



我的web应用程序有一套端到端的Cypress测试。当测试运行时,AJAX调用是针对真实的服务器进行的(即,请求不会被嘲笑或存根(。目前,我做了如下的事情来确保测试等待这些AJAX请求完成

// declare the AJAX request we will wait for
cy.route('POST', '/api/authenticate').as('authenticate')
// type the username and password and click the login button
cy.get('#username').type('john-doe')
cy.get('#password').type('secret')
cy.get('#login-button').click()
// wait for the AJAX request to complete before testing the response code
cy.wait('@authenticate')
cy.get('@authenticate').then(xhr => {    
expect(xhr.status).to.eq(200)
})

这看起来很冗长,有没有更简单的方法?我使用的是Cypress的最新版本,版本6.1.0。

cy.server((cy.route((在Cypress 6.0.0中已弃用。相反,柏树引入了cy.entercept((。所以你可以写一些类似的东西:

// declare the AJAX request we will wait for
cy.intercept('POST', '/api/authenticate').as('authenticate')
// type the username and password and click the login button
cy.get('#username').type('john-doe')
cy.get('#password').type('password')
cy.get('#login-button').click()
// wait till we get 200
cy.wait('@authenticate').its('response.statusCode').should('eq', 200)
//You can also assert request body and response body contents
cy.wait('@authenticate').its('request.body').should('include', 'username')
cy.wait('@authenticate').its('response.body').should('include', 'password')

在这里的例子中,它是这样写的。

cy.wait('@authenticate').should('have.property', 'status', 200)

不是一个巨大的节省,但它是一些东西:(

编辑:我刚刚注意到你说你有最新版本。如果那样的话,我会听从阿拉潘的建议。

最新更新