如何在cypress中使用while循环?运行此规范文件时,控制是否不进入循环?我轮询任务的方式是否正确?

Roh*_*ain 10 cypress

我轮询异步 POST 调用任务的方式是否正确???因为程序控制不会进入spec文件中的“while”循环。请帮忙!上一个查询:如何从 Cypress 自定义命令返回值

beforeEach(function () {
    cy.server()
    cy.route('POST', '/rest/hosts').as("hosts")
})


it('Create Host', function () {

    let ts =''
    let regex = /Ok|Error|Warning/mg 

    // Some cypress commands to create a host. POST call is made when I create a host. I want to poll 
    // task for this Asynchronous POST call.

    cy.wait("@hosts").then(function (xhr) {
        expect(xhr.status).to.eq(202)
        token = xhr.request.headers["X-Auth-Token"]
        NEWURL = Cypress.config().baseUrl + xhr.response.body.task
    })


    while((ts.match(regex)) === null) { 
        cy.pollTask(NEWURL, token).then(taskStatus => {
        ts= taskStatus
        })
    }
})

-------------------------

//In Commands.js file, I have written a function to return taskStatus, which I am using it in spec 
 file above

Commands.js -

Cypress.Commands.add("pollTask", (NEWURL, token) => {

    cy.request({
        method: 'GET',
        url: NEWURL ,
        failOnStatusCode: false,
        headers: {
            'x-auth-token': token
        }
    }).as('fetchTaskDetails')


    cy.get('@fetchTaskDetails').then(function (response) {
        const taskStatus = response.body.task.status
        cy.log('task status: ' + taskStatus)
        cy.wrap(taskStatus)
    })

})  
Run Code Online (Sandbox Code Playgroud)

Jon*_*vin 12

由于 cypress 的异步性质,您不能将 while/for 循环与 cypress 一起使用。Cypress 不会等待循环中的所有内容完成才再次开始循环。但是,您可以改为执行递归函数,并等待一切完成后再再次调用方法/函数。

这是一个简单的例子来解释这一点。您可以检查按钮是否可见,如果可见,则单击它,然后再次检查以查看它是否仍然可见,如果可见,则再次单击它,但如果不可见,则不会点击它。这将重复,按钮将继续被单击,直到按钮不再可见。基本上,方法/函数会被一遍又一遍地调用,直到不再满足条件为止,这完成了与循环相同的事情,但实际上适用于 cypress。

clickVisibleButton = () => {
        cy.get( 'body' ).then( $mainContainer => {
            const isVisible = $mainContainer.find( '#idOfElement' ).is( ':visible' );
            if ( isVisible ) {
                cy.get( '#idOfElement' ).click();
                this.clickVisibleButton();
            }
        } );
    }
Run Code Online (Sandbox Code Playgroud)

然后显然在你的测试中调用了this.clickVisibleButton()。我正在使用打字稿,并且此方法是在类中设置的,但您也可以将其作为常规函数来执行。


Dav*_*ini 1

while 循环对我不起作用,所以作为解决方法,我做了一个 for 循环,一种带有重试超时的 while 循环

let found = false
const timeout = 10000
for(let i = 0; i<timeout && !found;i++){
      if(..){
           // exiting from the loop
           found = true
      }
}
Run Code Online (Sandbox Code Playgroud)

我知道这对每个人都没有帮助。