Cypress.io - Assert no XHR requests to URL?

▼魔方 西西 提交于 2019-12-08 15:00:36

问题


When testing with cypress.io, is there a good way to assert that no XHR requests were made to a given URL?

I want to assert that a new foo is added when the "Save" button is clicked, but not when the "Cancel" button is clicked.

Something like this:

cy.route('POST', '/foos').as('postFoo');
cy.get('.cancel-button').click();
cy.route('@postFoo').should('not.have.been.called'); // (magic imaginary syntax!)

I've tried setting up the cy.route with an onRequest callback that does an assert.fail, but that's not failing the test when the the URL is called.

For now, I'm catching my (intentional) "no request occurred" errors like this:

cy.on('fail', (err, runnable) => {
  expect(err.message).to.include('No request ever occurred.');
  return false;
});  

cy.wait('@postFoo', { timeout: 0 }).then(xhr => {
  throw new Error('Unexpected API call.');
});

...which seems to be working, but it certainly doesn't feel very "cypress-y".


回答1:


You can re-alias your route and change its onRequest behavior to throw; however it's generally worse to assert that things didn't happen because they are non-deterministic. How long should you wait around for the error before moving on? :

cy.route({
  method: 'POST',
  url: '/foos',
  onRequest: () => {
    throw new Error('Whoops')
  }
})
cy.get('.cancel-button').click();
cy.wait(1000)  // give it one second to throw, then move on

Having assertions like this will only add unnecessary time to your tests. This type of test is know as Conditional Testing as mentioned in the Cypress Docs



来源:https://stackoverflow.com/questions/47295287/cypress-io-assert-no-xhr-requests-to-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!