Cypress: interrupt all tests on first failure

Viewed 13764

How to interrupt all Cypress tests on the first test failure?

We are using semaphore to launch complete e2e tests with Cypress for each PR. But it takes too much time.

I'd like to interrupt all tests on the first test failure.

Getting the complete errors is each developer's business when they develop. I just want to be informed ASAP if there is anything wrong prior to deploy, and don't have to wait for the full tests to complete.

So far the only solution I came up with was interrupting the tests on the current spec file with Cypress.

afterEach(() => {
        if (this.currentTest.state === 'failed') {
            Cypress.runner.end();
        }
    });

But this is not enough since it only interrupts the tests located on the spec file, not ALL the other files. I've done some intensive search on this matter today and it doesn't seem like this is a thing on Cypress.

So I'm trying other solutions.

1: with Semaphore

fail_fast:
  stop:
    when: "true"

It is supposed to interrupt the script on error. But it doesn't work: tests keep running after error. My guess is that Cypress will throw an error only when all tests are complete.

2: maybe with the script launching Cypress, but I'm out of ideas Right now here are my scripts

"cy:run": "npx cypress run",
"cy:run:dev": "CYPRESS_env=dev npx cypress run",
"cy:test": "start-server-and-test start http-get://localhost:4202 cy:run"
3 Answers

A little hack that worked for me

Cypress.Commands.add('interrupt', () => {
  eval("window.top.document.body.querySelector('header button.stop').click()");
});

The solution by @user3504541 is excellent! Thanks a ton. I already started giving up on using Cypress since these issues keep popping up. But in any case, here's my config:

support/index.ts

declare global {
  // eslint-disable-next-line
  namespace Cypress {
    interface Chainable {
      interrupt: () => void
    }
  }
}

function abortEarly() {
  if (this.currentTest.state === 'failed') {
    return cy.task('shouldSkip', true)
  }
  cy.task('shouldSkip').then(value => {
    if (value) return cy.interrupt()
  })
}

commands/index.ts

Cypress.Commands.add('interrupt', () => {
  eval("window.top.document.body.querySelector('header button.stop').click()")
})

In my case the Cypress tests were left pending indefinitely on the CI (Github action workflow) but with this fix they interrupt properly.

Related