6

I'm using multer to handle file uploads in my express app, and I'm also using node-sspi for ntlm authentication.

When uploading a file with curl, all works fine. But when I try doing the same with supertest it doesn't work.
Supertest does work with just the auth or just the upload, but I haven't succeed in working with both of them together.

working curl command: curl -u user:pass --ntlm -F upload=@filename http://localhost

Supertest code that does not work:

request(app)
    .post('/upload')
    .auth(username, password)
    .attach('upload', fileToUpload)
    .expect(200)

If I omit the attach or the auth - it works (of course I need to disable auth on server side, but in general I can upload)

So, someone knows how to upload a file with auth using supertest?

Also posted as an issue on supertest's GitHub

arieljannai
  • 2,124
  • 3
  • 19
  • 39

1 Answers1

3

Using Multer with Supertest

I solved this issue by making sure that the argument passed to upload.single(...):

router.post('/sessions', upload.single('someFileIdentifier'), function(req, res, next) {
    ...
}

Was the same name that I passed to supertest when attaching the file:

superTestAgent
  .post(`/sessions`)
      .attach('someFileIdentifier', `${__dirname}/test.csv`)
      .end((_err, res) => {
        ...
      })

Hope this helps! It's a subtle issue with an unhelpful error message:

MulterError: Unexpected field
at wrappedFileFilter (...)

Here's a link to the documentation: https://visionmedia.github.io/superagent/#multipart-requests

Mocking Authentication

Depending on how your auth middleware is set up, you can use jest.spyOn to mock it to automatically accept requests:

jest
  .spyOn(YourCustomAuthClass, 'requireUserAuth')
  .mockImplementation(async (_req, _res, next) => next())

Documentation on jest.spyOn: https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname

danbennett
  • 31
  • 6