mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.97k stars 519 forks source link

FormData with file fails in with-jest #2178

Closed joaopedrodcf closed 5 months ago

joaopedrodcf commented 5 months ago

Prerequisites

Environment check

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. image

Didn't test if this behaviour is coming from using Jest or from MSW.

There was this similar issue: https://github.com/mswjs/msw/issues/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

ernestostifano commented 5 months ago

Could be related to this? https://github.com/mswjs/http-middleware/issues/47

kettanaito commented 5 months ago

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)