How to set Content-Type of Supertest attachment

Viewed 8550

I came across a problem in my app that the Content-Type associated with an uploaded file was wrong if the file was sent from Microsoft Windows, giving application/octet-stream, while it was okay if sent from Mac, giving text/csv. After fixing my code to not rely on the mime type from the request, I would like to simulate that condition in one of my tests.

Given the following request, that includes JSON-stringified form fields and a file attachment, using supertest:

  request(app)
    .post('/some/where')
    .field('someFormData', JSON.stringify(formData))
    .attach('someFile', 'someFile.csv')
    .expect(400)
    .end(done);

How can I change the Content-Type for the attached file? Looking at Edge's Network tab, I would like to see the following for the request above:

-----------------------------7e13121340602
Content-Disposition: form-data; name="someFormData"

{.............}
-----------------------------7e13121340602
Content-Disposition: form-data; name="someFile"; filename="someFile.csv"
Content-Type: application/octet-stream

ÿØÿà

(The JSON string has been omitted with dots)

(Instead of showing text/csv, I want to simulate the wrong content type.)

3 Answers

Using attach's contentType option works for me:

request(app)
    .post('/validateCertificate')
    .set('Content-type', 'multipart/form-data')
    .field('passphrase', '1234')
    .attach(
      'pfx',
      './src/build-request/test-certs/correct.pfx',
      { contentType: 'application/x-pkcs12' },
    )
    .expect(200))

Or if you're sending a buffer as the file:

request(app)
    .post('/validateCertificate')
    .set('Content-type', 'multipart/form-data')
    .field('passphrase', '1234')
    .attach(
      'pfx',
      buffer,
      { contentType: 'application/x-pkcs12', filename: 'correct.pfx' },
    )
    .expect(200))
Related