Search code examples
javascriptcypressuncaught-exceptioncypress-cucumber-preprocessor

Turn on cypress uncaught:exception after turning it off


I'm currently trying to use Cypress for the first time and turn off cypress uncaught:exception during a certain test but I would like to turn it on once the test finished. How can I do that ? Thanks

PS: I disable it this way `

cy.on('uncaught:exception', () => false);

Solution

  • As well as cy.on() you can use cy.once() which turns off after the first catch.

    Or there is cy.off().

    Some examples from Cypress own code:

    cy.once('fail', (err) => {
      expect(err.message).to.match(/^A callback was provided ... /)
        .and.match(/ESOCKETTIMEDOUT|ETIMEDOUT/)
      done()
    })
    
    cy.on('log:added', handleAddLog)
    cy.on('fail', (err) => {
      cy.off('log:added', handleAddLog)
    })
    
    const onNavChanged = (event) => {
      if (event === 'page navigation event (load)') {
        cy.off('navigation:changed', onNavChanged)
        cb()
      }
    }
    
    cy.on('navigation:changed', onNavChanged)
    

    Named handler

    Note the "named" function used for the handler - this is so that same listener is turned off (you can have multiple listeners, and turn them off individually).

    So in your code

    const noError = () => false;
    cy.on('uncaught:exception', noError);
    ...  // later
    cy.off('uncaught:exception', noError);
    

    Type definitions

    namespace CypressOnceTests {
      Cypress.once('uncaught:exception', (error, runnable) => {
        error // $ExpectType Error
        runnable // $ExpectType Runnable
      })
    
      cy.once('uncaught:exception', (error, runnable) => {
        error // $ExpectType Error
        runnable // $ExpectType Runnable
      })
    }
    
    namespace CypressOffTests {
      Cypress.off('uncaught:exception', (error, runnable) => {
        error // $ExpectType Error
        runnable // $ExpectType Runnable
      })
    
      cy.off('uncaught:exception', (error, runnable) => {
        error // $ExpectType Error
        runnable // $ExpectType Runnable
      })
    }