Search code examples
cypress

Cypress.on after all tests in file have finished running


I have an it clause that runs 10 times, with this in it:

Cypress.on('test:after:run', test => {
    addContext(
      { test },
      {
        title: '...',
        value: {

The above gets executes for every one of the 10 iterations. Is there any way to make it execute only for the last iteration, or - after all iteration are done?

(I tried putting it in an after() clause but the addContext() function doesn't work then).


Solution

  • One thing to do would be to only run the code on a certain test

    Cypress.on('test:after:run', test => {
      if (test.fullTitle() === 'This is the tenth test') {
        addContext(...
    

    Or to eliminate the hard coded test name get creative with the test properties

    (this depends on the nesting of your test suite - the describe() blocks)

    Cypress.on('test:after:run', test => {
      const suite = cy.state('test').parent
      if (suite.tests.slice(-1) === test.fullTitle()) {
        addContext(...
    

    or fire just once inside the last test only

    it('This is the tenth test', () => {
      Cypress.once('test:after:run', test => {
        addContext(...
    

    or in after() hook

    after(() => {
      const test = cy.state('test')
      addContext(...
    

    or at the end of the spec

    (need more details to be exact)

    cypress.config.js

    module.exports = defineConfig({
      e2e: {
        setupNodeEvents(on, config) {
          on('after:spec', (spec, results) => {
            addContext(...
          })
        },
      },
    })