Search code examples
cypress

Send a REST message for each Cypress test result


Is there a way to call a REST api based for each cypress test result?

We have a zephyr test definition system, and we must use it's API (https://support.smartbear.com/zephyr-scale-server/api-docs/v1/ ) to change the status of each testcase our testers defined, as part of the automation processes we have in our company.

In my research the only solution we found was to use a Reporter (https://docs.cypress.io/guides/tooling/reporters) and then parse the results with a small script which generates the said REST calls for each test result.

I was wondering: is there any more elegant solution to call the zephyr app directly, via Cypress maybe?


Solution

  • I don't know what info zephyr requires, but there's plenty of hooks/events you can use.

    For example (at the top of the spec or in /support/index.js)

    Cypress.on('test:after:run', (test, runnable) => {
    
      console.log('test,runnable', test, runnable)
    
      const details = {
        projectKey: Cypress.env('zephyr-project-key'),
        testName: test.invocationDetails.relativeFile,
        status: test.status,
        error: runnable.err.message,
        retries: runnable.retries.length,
        duration: test.wallClockDuration,
        startTime: test.wallClockStartedAt
      }
      
      cy.request('POST', 'api/end/point', { body: details })
      // or native fetch('POST',...) if a particular hook complains about using cy.request
    })
    

    There's also

    on('after:run', (results) => {
      /* ... */
    })
    
    on('after:spec', (spec, results) => {
      /* ... */
    })
    
    on('after:screenshot', (details) => {
      /* ... */
    })
    

    Or (technically inside the test)

    afterEach(() => {
      const test = cy.state('test')
      const runnable = cy.state('runnable')
      /* ... */
    })