FormData with file fails in with-jest
joaopedrodcf opened this issue · 2 comments
Prerequisites
- I confirm my issue is not in the opened issues
- I confirm the Frequently Asked Questions didn't contain the answer to my issue
Environment check
- I'm using the latest
msw
version - I'm using Node.js version 18 or higher
Node.js version
v20.9.0
Reproduction repository
https://codesandbox.io/p/devbox/pensive-payne-k64jkx
Or alternatively
https://github.com/joaopedrodcf/bug-file-upload-form-data
Reproduction steps
Run pnpm test
on with-jest
and you gonna notice that we gonna receive a 201 instead of a 400
Current behavior
When we send a file in fetch and MSW handles the requests, getting the file in formData will always be empty.
Didn't test if this behaviour is coming from using Jest or from MSW.
There was this similar issue: #1913 that was closed and a test was created but in the test we used Blob instead of File
Expected behavior
Whenever we pass a File as FormData and receive it in MSW it should be of instance File and with the data we send so that this test passes
Could be related to this? mswjs/http-middleware#47
Hi, @joaopedrodcf. Thanks for reporting this.
You have a bug in your test code (or a handler). This is how you set the file on form data:
formData.set('file', file)
And this is how you retrieve the file in the handler:
const file = formData.get('orderFile')
The names of the form data fields don't match: file
vs orderFile
. Because of that, reading a non-existing field returns you null
.
You have to use the same field name if you wish to access that form data field in the handler. Here's the diff that fixes the issue:
--- a/examples/with-jest/mocks/handlers.ts
+++ b/examples/with-jest/mocks/handlers.ts
@@ -5,7 +5,7 @@ export const handlers = [
'https://api.example.com/upload-csv-file',
async ({ request }) => {
const formData = await request.formData();
- const file = formData.get('orderFile');
+ const file = formData.get('file');
PASS ./example.test.ts
✓ respects File in request body when invalid.csv (26 ms)