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

Viewed 930

I'm trying cypress API Intercepting and I have an error because website gives me multiple URL calls with the same name 'articles' and one are having status code 307 and the otherone has 200. how to find the article with status code 200?

Here is my code

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')
    })
})
})

})

this is the website network image

2 Answers

There's an answer here that looks like it will work

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(); // ...

You can use cy.get('@postArticles.all) when using cy.intercept(), not sure about cy.route() but you should switch to the new version.

Ref 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')
})
Related