Issue with google bucket image upload in a Cypress test

366 views Asked by At

I'm trying to create a Cypress test that involves uploading an image directly to a google storage bucket. I'm following this stack overflow suggestion: Upload File with Cypress.io via Request

and I have it to the point where the image file gets uploaded to the bucket without any errors during the upload. However when subsequently downloading the file from google, it's apparent that the image contents were corrupted.

The stack overflow example uses Cypress.Blob.base64StringToBlob() to create a blob to be uploaded. That method comes from this third party library which has been bundled with Cypress: https://github.com/nolanlawson/blob-util

Here's the code that I currently am working with:

Cypress.Commands.add('fileUpload', (url, fileName) => {
  const method = 'PUT';
  const fileType = 'image/png';

  cy.fixture(fileName).as('bin');

  cy.get('@bin').then( (bin) => {

    // File in binary format gets converted to blob
    // so it can be sent as Form data
    const blob = Cypress.Blob.base64StringToBlob(bin, fileType);

      // Build up the form
      const formData = new FormData();
      formData.set('file', blob, fileName);

      // Perform the request
      cy.rawFormRequest(method, url, formData, function (response) {
        cy.log(JSON.stringify(response));
      });
  });
});

Cypress.Commands.add('rawFormRequest', (method, url, formData, done) => {
  const xhr = new XMLHttpRequest();

  xhr.open(method, url);

  xhr.setRequestHeader('Content-Type', 'image/png');
  xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
  xhr.setRequestHeader('Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept');
  xhr.setRequestHeader('Access-Control-Allow-Methods',
    'GET, POST, PUT, DELETE, PATCH, OPTIONS');

  xhr.onload = function () {
    cy.log('success');
    done(xhr);
  };

  xhr.onerror = function (error) {
    cy.log('error');
    cy.log(JSON.stringify(error));
    done(xhr);
  };

  xhr.send(formData);
});

This is the image being uploaded:

But then when I go into the Google Storage GUI, it's apparent the image hasn't been uploaded cleanly:

I tried 2 of the other methods in the blob-util library: Cypress.Blob.arrayBufferToBlob() and Cypress.Blobl.imgSrcToBlob(), however again, although the file is uploaded without errors, when downloading or viewing in the google cloud GUI it's apparent that the file contents weren't uploaded cleanly.

0

There are 0 answers