1

I need to check that after the second click on the same button, an HTTP request is not sent. Is there a way to do it? I've already tried intercept and wait for this purpose, but can't make it work

Fody
  • 23,754
  • 3
  • 20
  • 37
YevS
  • 11
  • 2
  • Does this answer your question? [Is there a way to assert that a route has not been called in Cypress?](https://stackoverflow.com/questions/47354360/is-there-a-way-to-assert-that-a-route-has-not-been-called-in-cypress) – fkoessler Sep 28 '22 at 12:26

1 Answers1

0

A single-use intercept will probably work

const interceptOnce = (method, url, response) => {
  let count = 0
  return cy.intercept(method, url, req => {
    count += 1
    if (count < 2) {
      req.reply(response)
    } else {
      throw 'Error: button click caused two requests'    // cause test to fail
    }
  })
}

it('tests that two button clicks only sends a request on first click', () => {
  interceptOnce('POST', myurl, {stubbed response object})
  cy.get('button').click()
  cy.get('button').click()    // test fails here if a second request occurs
}) 

I'm not sure you even need to stub the response in this case.

Fody
  • 23,754
  • 3
  • 20
  • 37
  • I think this could be a little more resilient by also checking that the url is not the expected URL. Cypress (and web browsers) often make superfluous calls that we should probably account for. Maybe wrapping the `count` in an `if` statement on the url value? – agoff Apr 18 '22 at 13:26
  • 1
    If I'm following the logic, it would depend entirely on how broadly `myurl` matches API calls. But for a button submit, I don't see a problem in using a very targeted `myurl` value. – Fody Apr 18 '22 at 19:34
  • Agreed -- just thinking about projects I'm usually working on, if I were to attempt something like this, I'd want to make sure to only validate the specific call triggered by my app's button. (Also, the analytics calls on those buttons usually end up messing with things :( ) – agoff Apr 18 '22 at 21:25