Giter Club home page Giter Club logo

cypress-file-upload's Introduction

cypress-file-upload

GitHub license npm version build All Contributors monthly downloads downloads all time

File upload testing made easy.

This package adds a custom Cypress command that allows you to make an abstraction on how exactly you upload files through HTML controls and focus on testing user workflows.

Table of Contents

Installation

The package is distributed via npm and should be installed as one of your project's devDependencies:

npm install --save-dev cypress-file-upload

If you are using TypeScript, ensure your tsconfig.json contains commands' types:

"compilerOptions": {
  "types": ["cypress", "cypress-file-upload"]
}

To be able to use any custom command you need to add it to cypress/support/commands.js like this:

import 'cypress-file-upload';

Then, make sure this commands.js is imported in cypress/support/index.js (it might be commented):

// Import commands.js using ES2015 syntax:
import './commands';

All set now! πŸ’₯

Usage

Now, let's see how we can actually test something. Exposed command has signature like:

cySubject.attachFile(fixture, optionalProcessingConfig);

It is a common practice to put all the files required for Cypress tests inside cypress/fixtures folder and call them as fixtures (or a fixture). The command recognizes cy.fixture format, so usually this is just a file name.

HTML5 file input

cy.get('[data-cy="file-input"]')
  .attachFile('myfixture.json');

Drag-n-drop component

cy.get('[data-cy="dropzone"]')
  .attachFile('myfixture.json', { subjectType: 'drag-n-drop' });

Attaching multiple files

cy.get('[data-cy="file-input"]')
  .attachFile(['myfixture1.json', 'myfixture2.json']);

Note: in previous version you could also attach it chaining the command. It brought flaky behavior with redundant multiple event triggers, and was generally unstable. It might be still working, but make sure to use array instead.

Working with file encodings

In some cases you might need more than just plain JSON cy.fixture. If your file extension is supported out of the box, it should all be just fine.

In case your file comes from some 3rd-party tool, or you already observed some errors in console, you likely need to tell Cypress how to treat your fixture file.

cy.get('[data-cy="file-input"]')
  .attachFile({ filePath: 'test.shp', encoding: 'utf-8' });

Trying to upload a file that does not supported by Cypress by default? Make sure you pass encoding property (see API).

Working with raw file contents

Normally you do not need this. But what the heck is normal anyways :neckbeard:

If you need some custom file preprocessing, you can pass the raw file content:

const special = 'file.spss';

cy.fixture(special, 'binary')
  .then(Cypress.Blob.binaryStringToBlob)
  .then(fileContent => {
    cy.get('[data-cy="file-input"]').attachFile({
      fileContent,
      filePath: special,
      encoding: 'utf-8',
      lastModified: new Date().getTime()
    });
  });

You still need to provide filePath in order to get file's metadata and encoding. For sure this is optional, and you can do it manually:

cy.fixture('file.spss', 'binary')
  .then(Cypress.Blob.binaryStringToBlob)
  .then(fileContent => {
    cy.get('[data-cy="file-input"]').attachFile({
      fileContent,
      fileName: 'whatever',
      mimeType: 'application/octet-stream',
      encoding: 'utf-8',
      lastModified: new Date().getTime(),
    });
  });

Override the file name

cy.get('[data-cy="file-input"]')
  .attachFile({ filePath: 'myfixture.json', fileName: 'customFileName.json' });

Working with empty fixture file

Normally you have to provide non-empty fixture file to test something. If your case isn't normal in that sense, here is the code snippet for you:

cy.get('[data-cy="file-input"]')
  .attachFile({ filePath: 'empty.txt', allowEmpty: true });

Waiting for the upload to complete

Cypress' cy.wait command allows you to pause code execution until some asyncronous action is finished. In case you are testing file upload, you might want to wait until the upload is complete:

// start watching the POST requests
cy.server({ method:'POST' });
// and in particular the one with 'upload_endpoint' in the URL
cy.route({
  method: 'POST',
  url: /upload_endpoint/
}).as('upload');


const fileName = 'upload_1.xlsx';

cy.fixture(fileName, 'binary')
    .then(Cypress.Blob.binaryStringToBlob)
    .then(fileContent => {
      cy.get('#input_upload_file').attachFile({
        fileContent,
        fileName,
        mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        encoding:'utf8',
        lastModified: new Date().getTime()
      })
    })

// wait for the 'upload_endpoint' request, and leave a 2 minutes delay before throwing an error
cy.wait('@upload', { requestTimeout: 120000 });

// stop watching requests
cy.server({ enable: false })

// keep testing the app
// e.g. cy.get('.link_file[aria-label="upload_1"]').contains('(xlsx)');

I wanna see some real-world examples

There is a set of recipes that demonstrates some framework setups along with different test cases. Make sure to check it out when in doubt.

API

Exposed command in a nutshell:

cySubject.attachFile(fixture, processingOpts);

Familiar with TypeScript? It might be easier for you to just look at type definitions.

fixture can be a string path (or array of those), or object (or array of those) that represents your local fixture file and contains following properties:

  • {string} filePath - file path (with extension)
  • {string} fileName - the name of the file to be attached, this allows to override the name provided by filePath
  • {Blob} fileContent - the binary content of the file to be attached
  • {string} mimeType - file MIME type. By default, it gets resolved automatically based on file extension. Learn more about mime
  • {string} encoding - normally cy.fixture resolves encoding automatically, but in case it cannot be determined you can provide it manually. For a list of allowed encodings, see here
  • {number} lastModified - The unix timestamp of the lastModified value for the file. Defaults to current time. Can be generated from new Date().getTime() or Date.now()

processingOpts contains following properties:

  • {string} subjectType - target (aka subject) element kind: 'drag-n-drop' component or plain HTML 'input' element. Defaults to 'input'
  • {boolean} force - same as for cy.trigger, it enforces the event triggers on HTML subject element. Usually this is necessary when you use hidden HTML controls for your file upload. Defaults to false
  • {boolean} allowEmpty - when true, do not throw an error if fileContent is zero length. Defaults to false

Recipes

There is a set of recipes that demonstrates some framework setups along with different test cases. Make sure to check it out when in doubt.

Any contributions are welcome!

Caveats

During the lifetime plugin faced some issues you might need to be aware of:

  • Chrome 73 changes related to HTML file input behavior: #34
  • Force event triggering (same as for cy.trigger) should happen when you use hidden HTML controls: #41
  • Binary fixture has a workarounded encoding: #70
  • Video fixture has a workarounded encoding: #136
  • XML encoded files: #209
  • Shadow DOM compatibility: #74
  • Reading file content after upload: #104

It isn't working! What else can I try?

Here is step-by-step guide:

  1. Check Caveats - maybe there is a tricky thing about exactly your setup
  2. Submit the issue and let us know about you problem
  3. In case you're using a file with encoding and/or extension that is not yet supported by Cypress, make sure you've tried to explicitly set the encoding property (see API)
  4. Comment your issue describing what happened after you've set the encoding

I want to contribute

You have an idea of improvement, or some bugfix, or even a small typo fix? That's πŸ†’

We really appreciate that and try to share ideas and best practices. Make sure to check out CONTRIBUTING.md before start!

Have something on your mind? Drop an issue or a message in Discussions.

Contributors

Thanks goes to these wonderful people (emoji key):


James Hollowell

πŸ’»

lunxiao

πŸ›

Oliver O'Donnell

πŸ› πŸ’»

Peter Colapietro

πŸ“–

km333

πŸ›

Kevin Mui

πŸ’» πŸ€” πŸ‘€

Ben Wurth

πŸ› πŸ’»

Andreev Sergey

⚠️ πŸ’¬ πŸ’‘ πŸ’»

Guts

πŸ’¬

maple-leaf

πŸ’¬ πŸ’»

Daniel Mendalka

πŸ’¬

Chris Sargent

πŸ’¬

Ronak Chovatiya

πŸ’¬

Jan Hesters

πŸ’¬ πŸ›

John Molakvoæ

πŸ’¬

Phil Jones

πŸ›

Nicolas Gehring

πŸ›

David Pertiller

πŸ’¬ πŸ’»

Amy

πŸ›

Tomasz Szymczyszyn

πŸ“–

nitzel

πŸ’»

dirk

πŸ€”

Addie Morrison

πŸ›

Alec Brunelle

πŸ›

Gleb Bahmutov

πŸ€”

Jesse de Bruijne

πŸ“–

Justin Littman

πŸ’¬

harrison9149

πŸ›

jdcl32

πŸ’¬ πŸ’»

David Sheldrick

πŸ’»

Tom MacWright

πŸ’»

Andrew Hoddinott

πŸ’»

Eneko RodrΓ­guez

πŸ’»

Dmitry Nikulin

πŸ’»

Thiago Brezinski

πŸ›

Jack

πŸ’¬

Yoni Gibbs

πŸ›

benowenssonos

πŸ›

Aymeric

πŸ’¬

Alfredo Sumaran

πŸ›

x-yuri

πŸ€”

Tri Q. Tran

πŸ’»

Francis Chartrand

πŸ“–

Emil Ong

πŸ’»

Evgenii

πŸ“–

Joseph Zidell

🚧

Daniel Caballero

πŸ’»

Adrien Joly

πŸ“–

Jayson Harshbarger

πŸ’»

Andrico

πŸ“–

Paul Blyth

πŸ’»

Justin Bennett

πŸ“–

Shafiq Jetha

πŸ“–

tt rt

πŸ’»

Ed Hollinghurst

πŸ“–

anark

⚠️ πŸ’»

Michael Altamirano

πŸ’» πŸ’¬

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT

cypress-file-upload's People

Contributors

abramenal avatar adrienjoly avatar ajhoddinott avatar allcontributors[bot] avatar allout58 avatar anark avatar andrico1234 avatar benwurth avatar chartrandf avatar dependabot[bot] avatar dragorww avatar ds300 avatar ebazhanov avatar edhollinghurst avatar emilong avatar jdcl32 avatar jessedebruijne avatar jethas-bennettjones avatar josephzidell avatar jtneal avatar kmui2 avatar maple-leaf avatar michaeljaltamirano avatar mobiletainment avatar nisgrak avatar ollie-o avatar paulblyth avatar tmcw avatar triqi avatar zephraph avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cypress-file-upload's Issues

[Bug] CSV Uploads are still not working

Current behavior:

While the test won't fail for uploading the file, the file doesn't get read correctly.

Screenshot 2019-04-01 at 13 04 08

Instead of the csv data, an 'object promise' is being given to the input.
Here is the tests code:

  it.only('uploads a csv file, and logs the file', () => {
    cy.visit('/');
    cy.fixture('test.csv', 'ascii').then(fileContent => {
      console.log(fileContent);
      cy.get('input#CSVReader').upload(
        {
          fileContent,
          fileName: 'test.csv',
          mimeType: 'text/comma-separated-values',
          encoding: 'ascii'
        },
        { subjectType: 'input' }
      );
    });
  });

BTW, logging out fileContent gives the correct CSV data, see first line in screenshot.

Desired behavior:

The file should get uploaded correctly and trigger the onFileUpload method with the correct data.

Steps to reproduce: (app code and test code)

My set up is still mostly equivalent to when I created this issue:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import CSVReader from 'react-csv-reader';
 
function App() {
  function handleFileUpload(data) {
    const [rawCSVHeader, ...csvBody] = data;
    // Line 2 and 3 in the screenshot
    console.log(csvHeader);
    console.log(csvBody);
  }

  function handleFileUpload(f) {
    console.log(f);
  }

  return (
    <CSVReader
      cssClass="csv-reader-input"
      label="Select CSV"
      onFileLoaded={handleFileUpload}
      onError={handleError}
      inputId="CSVReader"
      inputStyle={{color: 'red'}}
    />
  );
}
 
ReactDOM.render(<App />, document.getElementById('root'))

Versions

Cypress: 3.1.5
Mac: Mojave 10.14.3
Browser: 73.0.3683.86
cypress-file-upload: 3.0.6

[Bug] Upload to hidden input doesn't work

Current behavior:

Uploading file to a hidden input ends up with below error:

CypressError: Timed out retrying: cy.trigger() failed because this element is not visible:

This element '<input#image-upload>' is not visible because it has CSS property: 'display: none'

Fix this problem, or use {force: true} to disable error checking.

https://on.cypress.io/element-cannot-be-interacted-with

There is no way to pass option { force: true } as an error message suggests. Current workaround is calling .invoke('show') before calling .upload():

    cy.fixture('avatar.jpg').then((fileContent) => {
      cy.get('=image-upload input')
        .invoke('show')
        .upload(
          { fileContent, mimeType: 'image/jpeg' },
          { subjectType: 'input' }
        )
    })

Desired behaviour:

.upload command accepts force option:

    cy.fixture('avatar.jpg').then((fileContent) => {
      cy.get('=image-upload input')
        .upload(
          { fileContent, mimeType: 'image/jpeg' },
          { subjectType: 'input', force: true }
        )
    })

Versions

  • cypress: 3.2.0
  • cypress-file-upload: 3.0.4
  • operating system: macOS 10.14.1

[Bug] failed to upload a vcf file

Current behavior:

cy.fixture('user.vcf').then(fileContent =>
        {
          cy.get('input[type="file"]').upload(
            { fileContent, fileName: 'user.vcf', mineType: 'base64' },
            { subjectType: 'input' },
          );
        });

image

Desired behavior:

upload a vcf file

Steps to reproduce: (app code and test code)

get a vcf file, thanks

Versions

Cypress: 3.1.5
OS: Windows10 professional
browser: Chromium 75

[Bug] How to upload to Angular's ngx-dropzone

Current behavior:

Hi!

I'm trying to use the provided examples to upload a file via drag n' drop to Angular's ngx-dropzone:

    const fileName = 'import-contacts-short.csv';

    cy.fixture(fileName).then(fileContent => {
      cy.get('[data-testid="dropzone"]').upload(
        { fileContent, fileName, mimeType: 'text/csv' },
        { subjectType: 'drag-n-drop' },
      );
    });

But I'm facing the following error:

image

This suggests that I should be passing a FileList, as .item is a property of this class, but I can't, since it is a readonly constructor. If ngx-dropzone is meant to be supported, is there any workaround to this?

Thanks in advance.

Desired behavior:

upload should support sending files via a FileList

[Bug] [cypress-file-upload error]: "encoding" is not valid.

Current behavior:

Running: cm/system/license.ts...                                   (34 of 54) 
  Estimated: 31 seconds


  System => License
    1) "before each" hook for "should display correctly"


  0 passing (57s)
  1 failing

  1) System => License "before each" hook for "should display correctly":
     [cypress-file-upload error]: "encoding" is not valid.
Please look into docs to find supported "encoding" values

Because this error occurred during a 'before each' hook we are skipping the remaining tests in the current suite: 'System => License'

Code that used to work

Cypress.Commands.add('uploadLicense', { prevSubject: true }, (subject, mode: AnalyticsMode, name: string, validUntil: Date, evaluation: boolean) => {
  if (!subject) {
    throw new Error('uploadLicense must be chained off your upload target!');
  }

  return cy.exec(
    `./node_modules/.bin/ts-node -T cypress/scripts/generate-license.ts "${mode}" "${name}" "${validUntil.toISOString()}" "${evaluation}"`,
    { env: Cypress.env() }
  ).then((result) => {
    cy.wrap(result, { log: false }).its('code').should('equal', 0);
    return cy.wrap(subject).upload(
      [{
        fileContent: btoa(result.stdout),
        fileName: 'license.lic',
        mimeType: 'text/plain',
        encoding: 'utf-8'
      }],
      {
        force: true,
        subjectType: 'drag-n-drop'
      });
  });
});

That targets an ng2-upload target in Angular.

Desired behavior:

To accept utf-8 again

Steps to reproduce: (app code and test code)

Versions

Cypress 3.4.0
Cypress File Upload 3.3.1

[Bug] Version 3.5.1 breaks drag/drop with Elm

Current behavior:

Since version 3.5.1, drag/drop operations on pages written in Elm appear to do nothing. The problem is that the JavaScript generated by the Elm compiler has the following code which is executed when a drop operation occurs:

function _Json_isArray(value)
{
	return Array.isArray(value) || (typeof FileList !== 'undefined' && value instanceof FileList);
}

The drop operation is accepted only if this function returns true. However in version 3.5.1 it now returns false. The value which is sent into this function is a FileList, but value instanceof FileList returns false. We suspect this is because value is created in a different context from the running Elm code (which, when run in Cypress, is inside an iframe). Below is a screenshot of the debugger showing some relevant info:

cypress-file-upload-filelist

Desired behavior:

Downgrading to version 3.5.0 seems to resolve the problem, and we suspect this issue is caused by this recent change (to fix #133).

We wondered if maybe a configuration option could be made available to define whether to use the DataTransferObject or to revert to the original behaviour.

Steps to reproduce: (app code and test code)

See repo here: https://github.com/yonigibbs/elm-drag-drop-cypress

Versions

  • Cypress: 3.8.0
  • Cypress File Upload: 3.5.1
  • OS: Ubuntu 18.04
  • Browser: Chrome or Electron in Cypress

[Bug]Tests using upload are crashing on jenkins

Current behavior:

image
File open dialog box pops up when cypress file upload plugin is used
image

Desired behavior:

File open dialog box should not pop up when cypress file upload plugin is used

Steps to reproduce: (app code and test code)

cy.fixture('OutputContract.txt').then((updatedcontractexcel) => {
cy.log(updatedcontractexcel)

        cy.readFile(updatedcontractexcel, 'base64').then(fileContent => {

            cy.get('input[type="file"]').upload({
                fileContent,
                fileName: updatedcontractexcel,
                mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                encoding: "base64"
            },
                {
                    uploadType: 'input'
                }
            )
            cy.xpath("/html/body/div[4]/div/div/div[2]/div/div[1]/div[3]/div[2]/input").type('DocumentationLink' + timestampval.getTimestamp())
            cy.xpath("/html/body/div[4]/div/div/div[2]/div/div[1]/div[3]/div[4]/input").type('Comments' + timestampval.getTimestamp())

            cy.xpath("//div[@class='btn-group btn-group-sm pull-right']//button[@class='btn btn-primary ng-binding'][contains(text(),'Upload')]").click({ force: true })
        })
    })

Versions

how to open an image file (help wanted)

Hello any help appreciated.
I think I have a very simple situation and I must be missing something.

I've installed the npm pkg and added the import to commands.js, and copied my file to fixtures

My html (Vue) is:

<input type="file"
           name="image"
           accept="image/*"
           @change="setImage"
      >

My Cypress test is:

  it('Uploads a jpg file', () => {
    cy.visit('uploadphoto')
    cy.fixture('myfile.jpg', 'base64').then(content => {
      cy.get('input').upload(content, 'myfile.jpg', 'image/jpeg')
    })
})

However when I run it the input is not populated with the file, and the @change event is not triggered either. This is a Vue project by the way.

Any help appreciated.

Cheers

Cannot upload json file[Bug]

Current behavior:

Error: JSON content could not be parsed
at JSON.parseWithDate (/****/node_modules/json.date-extensions/json.date-extensions.js:93:23)

image

Desired behavior:

I try to upload the json file

Steps to reproduce: (app code and test code)

cy.fixture(fileName).then(fileContent => {

cy.get('.hidden-upload').upload({ fileContent, fileName, mimeType: 'application/json'});
});

Versions

[Bug] `upload` doesn't upload files

Current behavior:

upload command attaches a file, not uploads anything.

Desired behavior:

Rename to attachFile or something. And you can make the interface easier to read while you're at it:

cy.get('input[type="file"]')
    .attachFile('upload.png', 'image/png');

compared to:

const fileName = 'upload.png';
cy.fixture(fileName).then(fileContent => {
    cy.get('input[type="file"]')
        .upload({fileContent, fileName, mimeType: 'image/png'});
});

can't upload video file - encoding fail

I cannot upload a video file with the current version (3.4.0)
e2e-test 2019-11-04 09-37-37

The code:

      cy.get('input.uppy-Dashboard-input').upload(
        { fileContent, fileName: 'sample_video.mp4', mimeType: 'video/mp4' },
        { subjectType: 'input' }
      );
    });

Also tried with 'binary' for encoding, same error.

cypress: 3.6.0
cypress-file-upload: 3.4.0
MacOS 10.14.6
Chrome v.78

.xml upload

I have a need to upload both .csv and .xml files. cypress-file-upload works great on .csv files, but I can't get it to work for .xml. The error I'm getting is: "encoding" is not valid. Please look into docs to find supported "encoding" values.

I looked at your list of encodings (https://github.com/abramenal/cypress-file-upload/blob/master/src/constants.js#L29) as well as Cypress's (https://docs.cypress.io/api/commands/fixture.html#Arguments) but I could not find one for .xml. I tried them all anyway, but all result in the same error.

Are .xml files supported? If not, do you have any plans to support them?

If they are supported and I'm just doing something wrong, here's my code

cy.fixture('file.xml').then(importfile => { //using default encoding, but I've tried all supported
cy.log(importfile) // this correctly logs the file's content for most encoding values
cy.get('#selectfile').upload(
{
fileContent: importfile,
fileName: 'file.xml',
mimeType: 'text/xml'
}
)
})

Thanks!

[Bug] Cannot upload video files

Hello again :)

The images processing works fine!
Though I started creating the video tests I have and it failed directly.
After some digging, it might be that the fixture base64 doesn't work with videos.

How can I use your plugin with hex or binary?
Or do you have any other workaround? :)

Thanks a lot!

[Bug] Upload with HTML file input does not work in Chrome 73

Current behavior:

File upload does not gets triggered when using Chrome v73 and higher.
There were no info in Chrome changelog:
https://developers.google.com/web/updates/2019/03/nic73

UPD:
Found related Chromium bug which seems to be fixed in corresponding Chrome release:
https://bugs.chromium.org/p/chromium/issues/detail?id=792336

Code snippets:

Electron 59: el.files = [testFile] trigger change on input
Chrome >69: el.files = [testFile] trigger change on input
Chrome 73: el.files = [testFile] not trigger change on input

This issue is fixed in #29.

Linked issue: cypress-io/cypress#3730

Desired behavior:

File upload should work seamlessly on any platform.

Versions

Chrome: >73

[Feature] In the GUI, show the number line of code being run rather than the step number

Current behavior:

When viewing running tests via the GUI or recordings online, there is a number associated with each step. This isn't really helpful for any of my personal use-cases and I'm unsure if it's really that helpful for anyone else.

Screen Shot 2019-07-25 at 10 10 06 AM

Desired behavior:

Would WOULD be sooooo helpful is if the number shown in the GUI for each step was in reference to the specific line of code being run. This would help to easily debug which specific line of the test is failing.
Screen Shot 2019-07-25 at 10 10 06 AM

Versions

Cypress 3.4.0
OSX 10.14.6
Chrome 75
Electron 61

Make file processing options object optional

Using [email protected]

If my test is

    cy.get('#file1').upload({
      fileContent: 'file contest',
      fileName: 'test.txt',
      mimeType: 'plain/text',
    })

then the plugin crashes trying to access subjectType of the undefined second object

Screen Shot 2019-08-01 at 10 25 11 AM

Adding the default subject type input fixes it, but should not even be required

    cy.get('#file1').upload(
      {
        fileContent: 'file contest',
        fileName: 'test.txt',
        mimeType: 'plain/text',
      },
      { subjectType: 'input' }
    )

[Bug] Tests using upload are crashing on jenkins/electron

Tests should be concluded with success like happens on chrome locally. But in our CI, jenkins, tests are be crashing, the CI don't continued tests after call the upload command. The same problem happens on terminal/electron execution. The test is passing, but not continued to the next step. It's freeze :(

    Given('I have an image {string} and I put on {string}',
        (fileName: string, input: string) => {
             cy.fixture(fileName).then(fileContent => {
                  const [, ext] = fileName.split('.')
                  
                  cy.get(`input[name="${input}"]`).upload(
                        {
                            fileContent,
                            fileName,
                            mimeType: `image/${ext}`,
                            encoding: 'base64'
                        },
                       { subjectType: 'input' }
                   )
             })
     })

We use cypress, 3.2 and cypress-cucumber-preprocessor.

[Bug] Drag and drop fails with angular applications using 'ng-file-upload' module for file uploads.

Current behavior:

Our application under test is created using angular which uses a third party package ng-file-upload for file upload functionality.

Cypress throws below error while executing test. After further investigation it is found that this is thrown from ngFileUpload service of third party package ng-file-upload which expects items object as part of dataTransfer object.

Uncaught TypeError: n.item is not a function

This error originated from your application code, not from Cypress.

When Cypress detects uncaught errors originating from your application it will automatically fail the current test.

This behavior is configurable, and you can choose to turn this off by listening to the 'uncaught:exception' event.

https://on.cypress.io/uncaught-exception-from-application

Desired behavior:

Drag and drop upload works with angular applications using nf-file-upload npm package or applications which expects items as part of dataTransfer object. Following code in handleDragDrop.js in local repo found working when tested.

export default ({ subject, force }, { files }) => {
  const dataTransfer = new DataTransfer();
  files.forEach(file => dataTransfer.items.add(file));
  cy.wrap(subject, { log: false }).trigger('drop', {
    force,
    dataTransfer: {
      files,
      items: dataTransfer.items,
      types: ['Files'],
    },
  });
};

Steps to reproduce: (app code and test code)

Pre-requisite
An angular application using ng-file-upload for file upload.

**Cypress test code **

      cy.fixture(filesToUpload[0].fileLocation).then((fileContent) => {
      cy.get('drag-area').upload(
        { fileContent, fileName: filesToUpload[0].fileName, mimeType: filesToUpload[0].mimeType },
        { subjectType: 'drag-n-drop' },
      );
      cy.get('.sb2-content-thumbnail-container').should('be.visible').contains(filesToUpload[0].fileName);

Versions

Cypress: 3.4.0
OS: Mac
Browser: Chrome 76

[Feature] adding webkitdirectory to support directory uploads

I would like to test a directory upload input, for that it should be enough to set the webkitRelativePath property in the created File object(s), eg:

File { 
name: "PANO_20190103_141758.jpg", 
lastModified: 1546521489000, 
webkitRelativePath: "images/2017/01/PANO_20190103_141758.jpg", 
size: 11591640, 
type: "image/jpeg" }

The File constructor does not support that, but you can force set it afterwards via Object.set. I'm using that approach already in my app if the user selects a single file instead of a directory.

Could that be implemented?

[Feature] Upload file using the button instead of input or drag&drop

Current behavior:

There is the possibility to upload the file in case the chosen selector is drag&drop or input, but now I faced with the case when the chosen selector is button. So when I point the SubjectType (button) in the code , the "invalid subjectType" error message is displayed after running the test.

export function uploadReceipt() {
const fileName = '593523b7eac85260172337.png';
cy.fixture(fileName).then(fileContent => {
cy.get('button[ngf-select="$ctrl.uploadFiles($file, $invalidFiles, item, $index)"]').click().upload(
{fileContent, fileName, mimeType: 'image/png'},
{subjectType: 'button'},
);
});
}

Desired behavior:

How to upload the file clicking on the button

Versions

Cypress package version: 3.5.0
macOS Mojave V10.14.6
Chrome 78

[Feature] Support File API polyfill

Current behavior:

It throws the following error:

TypeError: Failed to execute 'add' on 'DataTransferItemList': parameter 1 is not of type 'File'.

Desired behavior:

That the PDF file is uploaded

Steps to reproduce: (app code and test code)

I try to upload the PDF with the following different solutions of the code. Using force: true because elements are hidden:

TEST 1:

    cy.fixture('mypdffile-from-fixtures.pdf', 'base64').then(fileContent => {
        cy.get(`body [data-test="file-upload"][data-cy="mypdffile-from-fixtures.pdf"]`).upload(
            {fileContent, fileName: 'mypdffile-from-fixtures.pdf', mimeType: 'application/pdf'},
            {subjectType: 'input', force: true}
        );
    });

TEST 2:

    cy.fixture('mypdffile-from-fixtures.pdf', 'base64').then(fileContent => {
        cy.get(`body [data-test="file-upload"][data-cy="mypdffile-from-fixtures.pdf"]`).upload(
            {fileContent, fileName: 'mypdffile-from-fixtures.pdf', mimeType: 'application/pdf', encoding: 'base64'},
            {subjectType: 'input', force: true}
        );
    });

TEST 3:

    cy.fixture('mypdffile-from-fixtures.pdf', 'utf8').then(fileContent => {
        cy.get(`body [data-test="file-upload"][data-cy="mypdffile-from-fixtures.pdf"]`).upload(
            {fileContent, fileName: 'mypdffile-from-fixtures.pdf', mimeType: 'application/pdf', encoding: 'utf8'},
            {subjectType: 'input', force: true}
        );
    });

TEST 4:

    cy.fixture('mypdffile-from-fixtures.pdf').then(fileContent => {
        cy.get(`body [data-test="file-upload"][data-cy="mypdffile-from-fixtures.pdf"]`).upload(
            {fileContent, fileName: 'mypdffile-from-fixtures.pdf', mimeType: 'application/pdf'},
            {subjectType: 'input', force: true}
        );
    });

I run Cypress in a docker image and the image does see the file:

mva@mva-laptop:~/Documents/Projects/client$ docker run --rm --name=e2e_test --ipc=host -ti -v $(pwd)/config:/usr/src/app/config -v $(pwd)/cypress:/usr/src/app/cypress ${DOCKER_IMAGE} sh -c "ls -la cypress/fixtures/"
total 80
drwxr-xr-x 2 node node  4096 May 16 11:08 .
drwxrwxr-x 9 node node  4096 May 10 11:22 ..
-rw-r--r-- 1 node node 70969 May 16 11:08 mypdffile-from-fixtures.pdf

Versions

Cypress 3.2.0

Waiting for the upload to complete

Current behavior:

I have created a custom command that takes in the file name, mime type, encoding, and an attribute value to grab the specific component that will be handling the upload. Everything works, but I have found that Cypress will move on to the next test, even though the upload has not completed. Which can fail future tests waiting for the data from the upload.

Desired behavior:

I want to be able to track the output so I can halt Cypress from continuing on until upload is complete

Steps to reproduce: (app code and test code)

There really aren't reproducible steps, but I will include my custom command so you can see what I am currently doing.

Cypress.Commands.add(
  'upload_via_dropzone',
  (attrVal, fileName, mimeType, encoding, subjectType = 'drag-n-drop') => {
    return cy.fixture(fileName, encoding).then(fileContent => {
      cy.get(`[data-test="${attrVal}"]`).upload(
        { fileContent, fileName, mimeType, encoding },
        { subjectType, force: true },
      );
    });
  },
);

Versions

Cypres v3.3.1, OS: Mojave, Chrome

Upload CSV file using cypress

Current behavior:

I have a feature to upload CSV files in my application. and I'm trying the below lines of code. but it says that [cypress-file-upload error]: One or more field is invalid within given file(s).
Please look into docs to find supported "fileOrArray" values

Code Snippet

cy.server()
cy.route('POST', 'https://somesite/upload', 200).as('upload')
cy.get('input[type="file"]').upload(
  {
    fileContent: 'file content',
    fileName: 'SmallTapeCrackerTestFile.csv',
    contentType: 'text/csv',
  },
  { subjectType: 'input' }
)

// make sure upload has happened
cy.wait('@upload')

[Bug] -- cypress-file-upload does not work with Electron or headless Chrome during cypress tests

Current behavior:

I saw the Wrap but not the Trigger. File is not put into the file loader.

Desired behavior:

The file is attached to file loader.

Steps to reproduce: (app code and test code)

This is the code used:
cy.fixture('test.csv', 'ascii').then(content => { cy.get('[id=fileUpload]').upload(content, 'test.csv', 'application/plain'); cy.wait(10000); });

Versions

Windows 10, Electron 59

Engine Dependency needs to be updated

Current behavior:

When installing with yarn I received this error

error [email protected]: The engine "node" is incompatible with this module. Expected version ">8". Got "8.15.1"

Desired behavior:

I would like to be able to install this fine module on a machine running nodejs 8.x.x

I expect this can be fixed (and still retain the desired behavior) by changing the dependency requirement to >=8.

Steps to reproduce: (app code and test code)

  1. Install nodejs 8.15.1 (I expect it to be reproducible with any version of node 8).
  2. Initialize an npm package.json in a new directory and add [email protected] to the dependencies.
  3. Finally, run yarn.

Versions

  • NodeJS: 8.15.1
  • cypress-file-upload: 3.0.2
  • OS: Ubuntu 18.04
  • yarn: 1.13.0

[File upload on shadow dom component]

Current behavior:

I have a shadow dom file upload component where I can browse or drag and drop json or csv files. I tried the code you mentioned here. But didnt work. Can someone help me?

Desired behavior:

Should be able to drag and drop my files to shadow dom file upload component.

Versions

3.4.0, Windowws 10, chrome/electron

Thanks,
Dennis

[Feature] Folder upload

Add the ability to upload folders.

We have this functionality in one of our apps. We take the path from the webkitRelativePath from the File API which can't be overridden.

This is working fix for it:

Cypress.Commands.add('uploadFolder', ({ path, fileName, folderName }) => {
  cy.window().then(window => {
    class FileCopy extends File {
      get webkitRelativePath() {
        return `${folderName}/${fileName}`;
      }
    }

    window.File = FileCopy;

    cy.fixture(path).then(fileContent => {
      cy.get('input[type="file"].d-none').upload(...args);
    });
  });
});

[Bug] Path must be a string. Received { fileContent:...}

Hey! I'm having issues setting thing sup like you did on the examples.
I have a simple input with the id #file_upload_start

		cy.fixture('image1.jpg', 'base64').then(fileContent => {
			cy.get('#file_upload_start').upload(
				{ fileContent, fileName: 'image1.jpg', mimeType: 'image/jpeg' },
				{ subjectType: 'input' }
			)
			cy.get('#fileList tr[data-file="image1.jpg"]').should('contain', 'image1.jpg')
		})

The image exists in the fixtures directory.
I also tried without the base64, it also fails.

1 issue I encountered

 1) Open images in viewer "before all" hook for "See image.jpg in the list":
     TypeError: Path must be a string. Received { fileContent: '/9j/4AAQSkZJRgABAQEASABIAAD/....',
  fileName: 'image1.jpg',
  mimeType: 'mime/jpeg' }

Because this error occurred during a 'before all' hook we are skipping the remaining tests in the current suite: 'Open images in viewer'
      at assertPath (path.js:28:11)
      at Object.join (path.js:1232:7)
      at Object.get (/root/.cache/Cypress/3.2.0/Cypress/resources/app/packages/server/lib/fixture.js:45:16)
      at backendRequest (/root/.cache/Cypress/3.2.0/Cypress/resources/app/packages/server/lib/socket.js:290:34)
      at tryCatcher (/root/.cache/Cypress/3.2.0/Cypress/resources/app/packages/server/node_modules/bluebird/js/release/util.js:16:23)
      at Function.Promise.attempt.Promise.try (/root/.cache/Cypress/3.2.0/Cypress/resources/app/packages/server/node_modules/bluebird/js/release/method.js:39:29)
      at Socket.<anonymous> (/root/.cache/Cypress/3.2.0/Cypress/resources/app/packages/server/lib/socket.js:303:34)
      at emitMany (events.js:146:13)
      at Socket.emit (events.js:223:7)
      at /root/.cache/Cypress/3.2.0/Cypress/resources/app/packages/socket/node_modules/socket.io/lib/socket.js:503:12
      at _combinedTickCallback (internal/process/next_tick.js:131:7)
      at process._tickCallback (internal/process/next_tick.js:180:9)

[Bug] Force download

Current behavior:

I try to upload a file into a hidden input (with display:none).
I've first tried it using the subjectType input :

cy.fixture(image1).then(fileContent => { cy.get('.popupContent form input[type=file]').upload( { fileContent, fileName: image1, mimeType: 'application/pdf' }, { subjectType: 'input', force:true }, ); });

But I got the following error :
image

image

I tried then without the fileName option, by adding directly the variable

cy.fixture(image1).then(fileContent => { cy.get('.popupContent form input[type=file]').upload( { fileContent, image1, mimeType: 'application/pdf' }, { subjectType: 'input', force:true }, ); });

image

image

So I changed my mind and tried to use drag-and-drop to see if this would work.

cy.fixture(image1).then(fileContent => { cy.get('.popupContent form input[type=file]').upload( { fileContent, fileName: image1, mimeType: 'application/pdf' }, { subjectType: 'drag-n-drop', force:true }, ); });

I was nearly there when I noticed that drag-and-drop didn't implemented the force option.

image

So the new error was :

image

Desired behavior:

I guess that fixing the input error (which I don't really know how to) and implementing force on drag and drop handler would be awesome.

Steps to reproduce: (app code and test code)

--

Versions

Cypress : 3.3.1
cypress-file-upload : 3.1.2
Chromium 57

please provide recipes for laravel blade file upload

Hi,
I try to upload image file, but always got

[cypress-file-upload error]: One or more field is invalid within given file(s).
Please look into docs to find supported "fileOrArray" values

here is my laravel blade code, just common file upload html

<form method='post' action='' enctype="multipart/form-data">
          Select file : <input type='file' name='file' id='company-logo-file' class='form-control'><br>
          <input type='button' class='btn btn-info' value='Upload' id='company-logo-upload-button'>
        </form>

and this is my spec

        cy.fixture(fileImage, 'base64').then(fileContent => {
            cy.get('#company-logo-file').upload({
                fileContent,
                fileImage,
                mimeType: 'image/png',
                encoding: 'base64'
            }, {
                subjectType: 'input'
            })
            cy.contains(fileImage);
        })

I use cypress 3.5.0 with cypress-file-upload 3.4.0

I already followed recipes (i think the closest one is react html5 input, but still got same error)

Thanks :)

[Bug] CSV upload doesn't process

Current behavior:

Here is the code that I use:

  it.only('uploads a csv file, and logs the file', () => {
    cy.visit('/');
    cy.fixture('test.csv', 'ascii').then(fileContent => {
      cy.get('input#CSVReader').upload(
        {
          fileContent,
          fileName: 'test.csv',
          mimeType: 'text/comma-separated-values'
        },
        { subjectType: 'input' }
      );
    });
  });

Here is the error message:

InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Desired behavior:

The file should get uploaded correctly and trigger the onFileUpload method.

Steps to reproduce: (app code and test code)

Here is the code for the component:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import CSVReader from 'react-csv-reader';
 
function App() {
  function handleFileUpload(f) {
    console.log(f);
  }

  function handleFileUpload(f) {
    console.log(f);
  }

  return (
    <CSVReader
      cssClass="csv-reader-input"
      label="Select CSV"
      onFileLoaded={handleFileUpload}
      onError={handleError}
      inputId="CSVReader"
      inputStyle={{color: 'red'}}
    />
  );
}
 
ReactDOM.render(<App />, document.getElementById('root'))

The code for the test is above.

Folder structure:

src/App.js, cypress/fixtures/test.csv and cypress/integration/example_spec.js.

Versions

Cypress: 3.1.5
Mac: Mojave 10.14.3
Browser: 73.0.3683.86

[Bug] Doesn't fail on non-input targets

Current behavior:

When I pass something other than an input to upload (specifically a div containing an input), the library simply ignores it and acts like things are working correctly

Desired behavior:

Fail when invalid targets are passed

Versions

Cypress 3.3.1, Fedora Linux, Chrome 73

[Feature] Does upload.() return a promise?

Desired behavior:

Great library! Thanks for making this. Not sure if this is a bug or could be a new feature. I'd like upload() to wait until the file has been uploaded and then do something like click a button on the page. In the code below it seems that upload() is not waiting for the file to finish uploading before going into the second .then() block.

Current behavior:

cy.fixture('./3row.csv').then(fileContent => { cy.get('input[type="file"]').upload({ fileContent, fileName: './3row.csv', mimeType: 'text/csv' }).then(content => { cy.get('[data-cy="map-headers-container"]').contains('NEXT').click({force: true}); }) }); })

Versions

cypress 3.4

[Bug] pdf upload not working

Current behavior:

When uploading a pdf and having a file name with .pdf it throw TypeError: Cannot read property 'message' of undefined. After a lot of time i found out that the error occurs when a filename with extension .pdf is submitted. changing file extension to e.g. .jpg fixes the problem.

Desired behavior:

Pdf upload should work without problems

To upload a file with pdf ending

Steps to reproduce: (app code and test code)

//testFile is .pdf file
   cy.fixture('dataMocks.js').then(mocks => {
      cy.fixture(mocks.testFile, 'base64').then(fileContent => {
        cy.get('[data-cy="dropZoneFiles"]').upload(
          { fileContent, fileName: 'test.pdf', mimeType: 'application/pdf' },
          { subjectType: 'drag-n-drop' },
        );
      });

Versions

[Feature] Select events to trigger

Current behavior:

The actual lib call dragcenter, drop and dragleave events, some libs like Quasar needs others events.

In the case of Quasar I use the following code, modifing the lib and deleting the trigger to dragleave

cy.get(".q-uploader__list").trigger("dragover");
cy.fixture("archivoAlumnos.xls").then(fileContent => {
	cy.get(".q-uploader__dnd").upload(
		{ fileContent, fileName: "archivoAlumnos.xls", mimeType: "application/vnd.ms-excel", encoding: "utf8" },
		{ subjectType: "drag-n-drop" },
	);
});

Desired behavior:

The most ideal case should be the only use of fixture and upload command, without the previous trigger and deleting the dragleave event, a possibility to call user-defined events.

Thanks for the lib! πŸ˜„

'result' in FileReader has [object Object] instead of string after using upload method and reading file content

Current behavior:

Desired behavior:

Thanks for creating this library. I like how clear is to use it to test upload file functionality.

I took the library to test uploading a JSON file, read the content in the file, set the state and display file content on the layout. I found while using this library, a JSON file uploads, FileReader executes, but the result returns [objectObject] instead of an expected string.

When I upload a file in the real app the FileReader result correctly contains a string which is a content of the uploaded file.

I'm not sure if there is a bug in the library or I missed something in my implementation which can be seen below.

Steps to reproduce: (app code and test code)

Please find the code that I use:

// implementation of file input

<input type="file" className="file-input" name="file" accept=".json" onChange={handleUploadFile}/>

// implementation of handleUploadFile

const handleUploadFile = (e: ChangeEvent<HTMLInputElement>) => {
    const file = e && ((e.target as HTMLInputElement).files as FileList)[0];
    if (file) {
      const fileReader = new FileReader();
      fileReader.onloadend = (e) => {
        const content = fileReader.result as string;
        
        console.log(content) // displays [object Object] instead of string
        setInput(JSON.parse(content));
        handleJSONChange(JSON.parse(content), null, 'input');
      }
      fileReader.readAsText(file);
    }
  }

// test

it.only('should upload a file', () => {
  const fileName = 'upload-file.json';
  const output = '{"sample": "json"}';

  cy.fixture(fileName)
      .then(fileContent => {
         cy.get('.file-input').upload({fileContent, fileName, mimeType: 'application/json'}, { subjectType: 'input', force: true })
       })
       .should(() => {
             cy.get('#input > .jsoneditor > .jsoneditor-outer > .ace_editor > textarea')
                 .should(($div) => {
                     const values = $div.map((i, el) => Cypress.$(el).text())
                     const result = values
                          .get()
                          .map(line => line.trimLeft())
                          .join('')

                     expect(result).to.eq(JSON.stringify(output))
                 });
         });
});

Versions

first run fail of upload

Problem with uploader (for React);

Here is the html:

      <div style={{ display: 'none' }} data-cy="uppy-input">
        <div className="UppyForm" ref={uppyFormEl} />
      </div>

Rendered DOM looks like this:

<div data-cy="uppy-input" style="display: none;">
  <div class="UppyForm">
    <div class="uppy-Root uppy-FileInput-container">
       <input class="uppy-FileInput-input" type="file" name="files[]" multiple="" accept="image/*" style="">
    </div>
  </div>
</div>

This is the test:

    cy.fixture('images/bucephalus.jpg', 'base64', { timeout: 12000 }).then(
      fileContent => {
        cy.get('[data-cy=uppy-input] input', {
          timeout: 12000,
          force: true,
        }).upload(
          { fileContent, fileName: 'bucephalus.jpg', mimeType: 'image/jpeg' },
          { subjectType: 'input' }
        );
      }
    );

On first run, Cypress throws this:
uppy timeout

This always happens on first run of the spec - subsequent runs usually (not always) pass.

Cypress 3.4.1, 3.5; cypress-file-upload: 3.1.1, 3.4.0; React 16.8.1; MacOS 10.14.6; Chrome 78.0.3904.70

[Bug] Binary fixture upload

Not sure if that should be considered a bug in cypress-file-upload since there is also an ongoing discussion for cypress itself: cypress-io/cypress#1558. Still, I think it makes sense to point out that there is a problem with binaries.

Current behavior:

I am trying to upload binary files constituting a shapefile.
I specify "binary" as enconding, both for fixture and upload payload.
I get InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded error when doing the upload.

Desired behavior:

Upload works correctly with encoding specified as "binary".

Steps to reproduce: (app code and test code)

cy.fixture("Test.shp", "binary").then(data => {                                                                                                          
  cy.get('#upload').upload(
    { fileContent: data, fileName: "Test.shp", encoding: "binary", mimeType: "application/octet-stream" },
    { subjectType: 'input' }
  );                                                                                 
});

Workaround

Use "base64" as encoding (both for fixture loading and upload).

Versions

cypress 3.2.0
cypress-file-upload: 3.1.1
Linux Mint 18.2 Cinnamon 64-bit

[Bug] Not adding file correctly "[object Promise]" contents always

Current behavior:

cy.get('input').upload(
      [{
        fileContent: 'foobar',
        fileName: 'dynamic.lic',
        mimeType: '',
        encoding: 'utf-8'
      }],
      {
        force: true,
        subjectType: 'drag-n-drop'
      });

Against an ng2-file-upload target https://github.com/valor-software/ng2-file-upload

The HTTP request then made by angular is:

------WebKitFormBoundaryuPJXUTfgfFPBd4cB
Content-Disposition: form-data; name="file"; filename="dynamic.lic"
Content-Type: application/octet-stream

[object Promise]
------WebKitFormBoundaryuPJXUTfgfFPBd4cB--

Which is wrong as it should be the file contents.

The angular app logging shows the file in ng2-file-upload as:

image

Desired behavior:

Should add the file properly

Steps to reproduce: (app code and test code)

Maybe try targeting these demo controls https://valor-software.com/ng2-file-upload/

Versions

Cypress 3.2.0
MacOS latest
Node LTS
Chrome

[Feature] Compatibility with shadow dom

Current behavior:

Can this plug-in work with shadow dom as well ?
When I tried to use it with our application I got an exception the element is detached from dom.
It would be really nice if this plug-in can work with shadow-dom.

Desired behavior:

This plug-in works with shadow-dom. If it is working with shadow-dom if an example could be added to the read-me page would be really helpful.

Versions

PDF upload returning unsupported fileOrArray value error even with encoding workaround

I have reviewed this reported issue given that it is very similar to my error but the encoding workaround does not seem to be working for me. #58 Any help would be great!

I've followed the steps on the README but have not been able to figure out my issue yet. I'm still quite new to Cypress and javascript in general, so I apologize if I'm missing something obvious. I added and am fetching [name="cy-dropzone"] rather than data-cy=... as shown in the readme example. I have attempted to use utf8 and base64 but neither worked.

Experiencing this error:
[cypress-file-upload error]: One or more field is invalid within given file(s). Please look into docs to find supported "fileOrArray" values

Current code block

    const fileName = 'testFile.pdf';
    cy.fixture(fileName).then(fileContent => {
      cy.get('[name="cy-dropzone"]', { force: true }).upload(
        { force: true },
        { fileContent, fileName, mimeType: 'application/pdf', encoding: 'base64' },
        { subjectType: 'drag-n-drop', force: true },
      );
    });

Screen Shot 2019-07-24 at 8 08 03 AM

[Bug] - Trying to upload a `video/mp4` with `binary` encoding fails

Current behavior:

image

image

$ file -I test_asset_02.mp4

test_asset_02.mp4: video/mp4; charset=binary

Desired behavior:

Trying to upload a video/mp4 with binary encoding fails, I used the same command for Jpegs and such and they work perfect.

Steps to reproduce: (app code and test code)

Upload an video/mp4 with binary encoding

Versions

Cypress: 3.5.0 , operating system: locally OSX but running against a production server (Unix), browser: Electron

[Bug] Files upload are blank

Current behavior:

When I upload a file (.PDF) the file is upload but the PDF is blank.

Desired behavior:

I Want to upload the PDF as it exist

Steps to reproduce: (app code and test code)

When("I enter the Visite mΓ©dicale au travail information", () => {
    const fileName = "cv644.pdf";
    cy.fixture(fileName).then(fileContent => {
      cy.xpath('//input[@class="file-input"][1]').upload({
        fileContent,
        fileName,
        mimeType: "application/pdf"
      });
    });
    cy.waitUntil(() =>
      cy.xpath('//i[@class="icon-check"][1]').should("be.visible")
    );
    cy.get("[id^=day-JJ]").type("25");
    cy.get("[id^=month-MM]").type("08");
    cy.get("[id^=year-AAAA]").type("2025");
    cy.get("[id^=profession-crivezici-Mtiersconcerns]").type("Boulanger");
    cy.xpath('//div[@role="menu"]/.//span[@role="menuitem"]')
      .contains("Boulanger")
      .click();
    cy.xpath('//button[@type="button"][1]')
      .eq("4")
      .click();
  });

The PDF is in my fixture file

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.