Retries in Cypress and Before hooks

Viewed 478

Morning all. I have a slightly unusual design to my tests. A typical example might be

describe('1', () => {
   describe('2', () => {

       before()

       describe('3', () => {
           it('1')
           // ...
           it('n')
        });
    });
});

If there is a failure in one of the individual tests (it 1..n), I want to re-run ALL of those tests, and run the "before" code first too - ie from "describe 2". If I use a before hook then re-runs don't trigger that again. If I change to a beforeEach, then it gets called before each and every "it" block, which I don't want.

Effectively, each it block is a test check, describe 3 is a test step, describe 2 a test spec, and describe 1 a test "group"

Can anyone suggest a way I can re-run a test spec (describe 2) when one test check fails, including re-running the before code for that spec?

(I know this is probably anti-pattern etc, but....)

1 Answers

You can externalise the before() callback function, and use the test:after:run event to trigger it on a retry.

I haven't tested this extensively, but the gist is

const beforeCallback = () => {...}

before(beforeCallback)

Cypress.on('test:after:run', (result) => {
  if (result.currentRetry < result.retries && result.state === 'failed') {
    beforeCallback()
  }
})

it('fails', {retries:3}, () => expect(false).to.eq(true)) // failing test to check it out
Related