How to handle FormData in Miragejs?

704 Views Asked by At

Miragejs handles json out-of-the-box but seems to be unable to handle FormData. When I post FormData and log the received request in mirage endpoint, request.requestBody is empty.

Simplified code examples:

  • POSTing FormData:
const testFile = new File(['hello'], 'hello.png', { type: 'image/png' });
const formData = new FormData('file', testFile);
fetch('https://localhost:3000/api/endpoint', {method: 'POST', body: formData});
// ...
  • receiving POST in mirage mock server:
this.post('/endpoint', (schema, request) => {
  console.log('request:', request);
  // request.requestBody is an empty string!  
});

Possibly a related issue: https://github.com/miragejs/ember-cli-mirage/issues/74

1

There are 1 best solutions below

0
Juuso Ohtonen On

It's possible to cast the request.requestBody to FormData and then parse the file.

Shortening the excellent solution described in How to handle uploading and parsing files in your frontend app tests:

this.post('/endpoint', (schema, request) => {
  const readFile = async (file: File): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onerror = () => reject(new Error('There was an error reading the file!'));
      reader.onload = () => resolve(reader.result as string);
      reader.readAsText(file);
    });
  const formData: FormData = request.requestBody as unknown as FormData;
  const uploadFile: File = formData.get('file') as File;
  const fileContents: string = await readFile(uploadFile);
  console.log('Uploaded file contents:', fileContents);
});