Steve Staple
Steve Staple

Reputation: 3289

Is there any way I can output a file from my Cypress test runner?

There are error files generated by an API that my tests call. The errors are output to a file, & screen displays the error file id. I can download these files using the apiKey & the fileID whilst the test is still running, but after that, it is gone. It would be very handy if I could output this file to my browser (via a download) so I can see it. At the moment, I can only get it by adding cy.pause() to my test code to pause the test after the error file has been created.

Line of code that shows me fileID:

cy.log('resultsCsvFileId: ' + res.import.resultsCsvFileId);

Upvotes: 1

Views: 5430

Answers (1)

Kondasamy Jayaraman
Kondasamy Jayaraman

Reputation: 1864

You can actually use cy.writeFile() as below,

cy.request('https://dummy.url').then((response) => {
  cy.writeFile('cypress/fixtures/response.csv', response.import.resultsCsvFileId)
})

You can refer the docs here - https://docs.cypress.io/api/commands/writefile.html#JSON

But, this overwrite the file every time. Here, is the workaround to append the required data to a CSV file,

  1. Install npm package csvdata https://www.npmjs.com/package/csvdata

    npm install --save-dev csvdata

  2. In the cypress project -> plugins index.js file place the below code,

const csvdata = require('csvdata')
on('task', {
    log(message) {
        csvdata.write('./logs.csv', message, {
            append: true,
            header: 'stats,numusers'
        })
        return null
    }
})

  1. Then from now on, all the log task will get appended to the CSV file,

describe('My First Test', function() {
    it('Visits the Kitchen Sink', function() {
      cy.visit('https://example.cypress.io')
      cy.contains('type').then(($el) => {
          var data = "inService, 30";
          cy.task('log', data)
      })
    })
})

Reference: https://github.com/cypress-io/cypress/issues/1249

Update 1: The issue specified above is now resolved and append option is now available,

cy.writeFile('path/to/message.txt', 'Hello World', {flag: "a+"}))

Upvotes: 4

Related Questions