如何使用 cypress 而不是 307 或其他一些来查找状态代码为 200 的文章

how to find article with status code 200 using cypress instead of 307 or some other one

我正在尝试 cypress API 拦截,但我遇到了一个错误,因为网站给了我多个 URL 具有相同名称 'articles' 的调用,其中一个具有状态代码 307 和别人有200,如何找到状态码为200的文章?

这是我的代码

it('should logged in',()=> {
cy.wait(3000)
cy.contains('New Article').click()
cy.get('fieldset').then(article =>{
    cy.server()
    cy.route('POST', '**/articles').as('postArticles')         
    cy.wrap(article).find('[placeholder="Article Title"]').type('New Article')
    cy.wrap(article).eq(2).type('nothing')
    cy.wrap(article).eq(3).type('some text')
    cy.wrap(article).find('button').contains(' Publish Article ').click()
    cy.contains('Home').click()
    cy.wait('@postArticles')
        cy.get('@postArticles').then(xhr =>{
        console.log(xhr)
        expect(xhr.status).to.equal(200)
        expect(xhr.request.body.article.body).to.equal('some text')
        expect(xhr.request.body.article.description).to.equal('nothing')
        expect(xhr.request.body.article.title).to.equal('New Article')
    })
})
})

})

这里有一个看起来可行的答案

How to wait for a successful response in Cypress tests

function waitFor200(routeAlias, retries = 2) {  // bump up retries to suit your test
  cy.wait(routeAlias).then(xhr => {
    if (xhr.status === 200) return // OK
    else if (retries > 0) waitFor200(routeAlias, retries - 1); // wait for the next response
    else throw "All requests returned non-200 response";
  })
}

waitFor200('@getSessionInfo'); 

// Proceed with your test
cy.get('button').click(); // ...

在使用cy.intercept()时可以使用cy.get('@postArticles.all),不确定cy.route(),但您应该切换到新版本。

参考 Asserting Network Calls from Cypress Tests

cy.contains('Home').click()

cy.wait('@postArticles')   // only waits the first call!

cy.contains('Global Feed')  // wait for something indicating the POSTs have finished

cy.get('@postArticles.all').then(xhrs => {

  expect(xhrs.map(xhr => xhr.status)).to.include(200)       // one of them is "200"

  const twoHundred = xhrs.find(xhr => xhr.status === 200)  // get it

  expect(twoHundred.body.article.body).to.equal('some text')
  expect(twoHundred.body.article.description).to.equal('nothing')
  expect(twoHundred.body.article.title).to.equal('New Article')
})