question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

can cy.writeFile write any type of document?

See original GitHub issue

Current behavior:

After a download attempt an excel file with cy.request() command, response.body can be saved by using cy.writeFile command with any filename and extension (like ‘text.xlsx’) but file cannot be open.

Desired behavior:

Any type of file should be saved with any extension and can be opened properly.

Versions

Cypress: 3.0.1 Operating system: Mac Browser : Electron 59

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:15 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
roma-glushkocommented, Mar 8, 2019

@WesleySSmith thank you very much, this idea helped me to create a workaround. Maybe I put it here, just in a case someone needs it, too:

plugins/index.js:

const request = require('request');
const fs = require('fs');

module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config

    on('task', {
        downloadPdf(args) {
            const directory = args.directory;
            const cookieHeader = args.cookies.map(e => e.name + '=' + e.value).join(';');

            return new Promise((resolve, reject) => {
                request({url: args.url, encoding: null, headers: {Cookie: cookieHeader}}, function(err, res, body) {
                    if (!res) {
                        return reject(new Error('No response'));
                    }

                    if (res.statusCode !== 200) {
                        return reject(new Error('Bad status code: ' + res.statusCode));
                    }

                    const contentDisposition = res.headers['content-disposition'];

                    if (!contentDisposition || contentDisposition.indexOf('inline') === -1) {
                        return reject(
                            new Error('Broken response: does not contain content-disposition of inline file type')
                        );
                    }

                    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    const matches = filenameRegex.exec(contentDisposition);

                    if (matches == null || !matches[1]) {
                        return reject(new Error('Broken response: does not contain filename'));
                    }

                    const fileName = matches[1].replace(/['"]/g, '') + '.pdf';

                    fs.writeFileSync(directory + fileName, body);
                    resolve(body);
                });
            });

        }
    });

};

support/commands.js:

Cypress.Commands.add('downloadPdf', (url, directory) => {
    return cy.getCookies().then(cookies => {
        return cy.task('downloadPdf', {url: url, directory: directory, cookies: cookies });
    });
});

In my test file:

cy.downloadPdf(pdfUrl, 'temp/');

My plugin/index.js contains a bit more code, because I need to parse response headers in order to get correct PDF filename.

Also, I reported this issue in a separated task: https://github.com/cypress-io/cypress/issues/3576 So it’s already approved and marked as a bug and hopefully we won’t need to use such workarounds soon 🙌

4reactions
miketeocommented, Aug 9, 2018

I am having a similar issue here, except that I am dealing with zip files.

cy.log('Package URL is ' + downloadURL)
cy.request(downloadURL).then((response) => {
    expect(response.status).to.be.equal(200)
     cy.log(response.body.length)
     cy.writeFile('cypress/work/downloadTest.zip', response.body, 'binary')
})

The logged response.body.length (50505) is of different value from the original file size on the server and the content-length header (53398) in the response. If I manually download the zip file using another web browser, the saved file can be opened correctly.

I suspect cy.request is performing some post-processing on the response body, even though the response’s content-type is set to application/zip. I have repeated the same test a number of times; the response.body.length is always the same length, so it is clearly not a network issue.

console screenshot

Read more comments on GitHub >

github_iconTop Results From Across the Web

writeFile - Cypress Documentation
cy.writeFile() requires the file be successfully written to disk. Anything preventing this such as OS permission issues will cause it to fail.
Read more >
Can I use cy.writeFile() to write a formatted txt file?
No, .txt files generally do not have bold formatting, but you could use an HTML file.
Read more >
How to use writeFile and readFile in Cypress? - TestersDock
In this article, we will learn to use write File (write to a file) and readFile (read from a file) in cypress.
Read more >
How do I write to a file in Cypress? - YouTube
Chapters. View all · Introduction · Introduction · Introduction · CY WRITE - Storing data in a JSON File. · CY WRITE -...
Read more >
Files | Cypress examples (v9.0.0) - Gleb Bahmutov
To write to a file with the specified contents, use the cy.writeFile() command. // https://on.cypress.io/writefile // You can write ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found