Search code examples
cypressend-to-end

Is there a way to access test case and test suite details in Cypress?


I am trying to make a JSON file to store the details of Cypress Tests, but I don't know how to access them.
The details I need:
1- Test case (it block) title
2- Test suite (describe block) title
3- Number of current retry
And inside the after each hook
3- Test case state (passed, failed, skipped)
4- Test case duration
5- Test case Error message (in case the test case failed)


Solution

  • Look at this question for relevant details: How to find the calling test in cypress custom command

    Also, you can simply copy and use one of these functions:

    // To get the test case title (it block description)
    function testCaseTitle(inHook){
      if(inHook) // If called inside a hook
        return Cypress.mocha.getRunner().suite.ctx.currentTest.title;
      return Cypress.mocha.getRunner().suite.ctx.test.title;
    }
    
    
    
    // To get the test suite title (describe block description)
    function testSuiteTitle(inHook){
      if(inHook) // If called inside a hook
        return Cypress.mocha.getRunner().suite.ctx._runnable.parent.title;
      return Cypress.mocha.getRunner().suite.ctx.test.parent.title;
    }
    
    
    
    // To get the current test retry 
    function testCaseRetry(inHook){
      if(inHook) // If called inside a hook
        return Cypress.mocha.getRunner().suite.ctx.currentTest._currentRetry;
      return Cypress.mocha.getRunner().suite.ctx.test._currentRetry;
    }
    // To get the total number of retries
    function totalRetries(inHook){
      if(inHook) // If called inside a hook
        return Cypress.mocha.getRunner().suite.ctx.currentTest._retries;
      return Cypress.mocha.getRunner().suite.ctx.test._retries;
    }
    
    
    
    // To get the test case state in after each hook
    function testCaseState(){
      return Cypress.mocha.getRunner().suite.ctx.currentTest.state;
    }
    // Or Alternatively, to test whether the test case has passed in after each hook
    function hasPassed(){
      return Cypress.mocha.getRunner().suite.ctx.currentTest.state == 'passed';
    }
    
    
    
    // To get the test case duration in seconds in after each hook
    function testCaseDuration(){
      return (Cypress.mocha.getRunner().suite.ctx.currentTest.duration/1000).toFixed(2)+' sec';
    }
    
    
    
    // To get the error message of a failing test case 
    function testCaseErrorMessage(){
      return Cypress.mocha.getRunner().suite.ctx.currentTest.err.message;
    }