cypress: Posting formData using cypress doesn't work
Current behavior:
Uploading file via POST request of formData doesn’t work.
Desired behavior:
Being able to post formData using cypress POST request.
Steps to reproduce:
The following code doesn’t work.
const formData = new FormData();
formData.set('file', new File(['data'], 'upload.txt'), 'upload.txt');
cy.request({
method: 'POST',
url: '/upload/end/point',
body: formData,
headers: {
'content-type': 'multipart/form-data',
},
});
Versions
cypress@2.1.0 ubuntu 16.04 LTS Chrome 66.0.3359
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 26
- Comments: 32 (5 by maintainers)
cc: @srinivasrk @ahmehri
I was able to get a formData submitted with a combination of a mix of answers I found.
I hope this helps you.
Add this to support/commands.js:
Then you’d be able to do the following in your tests:
Thanks @shwarcu this is pretty much everything you need. There are a couple of little things you need to make sure you do with this.
It would really be ideal for Cypress to add support for multipart/form-data requests using their cy.request() command, but this is a reasonable workaround for the moment. This is very picky on how everything is set up and executed, so it is likely to break with future Cypress updates.
lmfao is all I can say.
If XHR request is part of your test setup and you need its response later on, here is the solution I worked out:
In a helper file you can define a function to execute the request:
Using helper function you can define a specific request to your API as:
And your custom command:
Now in your fixtures you can prepare following files:
And in your test you can easily handle such image upload:
This will get necessary information about image from the json fixture and then get the binary and upload it.
This worked for me with cypress 4.8.0
I would hope this issue can get fixed the right way. For us, the workaround does not work due to CORS since we are doing direct request to api in testing instead of of web server