0
0
ExpressHow-ToBeginner · 3 min read

How to Test File Upload in Express: Simple Guide

To test file upload in Express, use the supertest library to simulate HTTP requests with attached files. Combine it with multer middleware in your Express app to handle file uploads, then write tests that send files and check the response.
📐

Syntax

Use supertest to send a POST request with a file using .attach(fieldName, filePath). The Express app should use multer middleware to process the uploaded file from the request.

  • app.post('/upload', upload.single('file'), handler): Express route with multer handling one file named 'file'.
  • request(app).post('/upload').attach('file', 'path/to/file'): Test sending a file named 'file'.
javascript
const request = require('supertest');
const express = require('express');
const multer = require('multer');

const upload = multer({ dest: 'uploads/' });
const app = express();

app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) return res.status(400).send('No file uploaded');
  res.status(200).send('File uploaded');
});

// Test example
request(app)
  .post('/upload')
  .attach('file', 'path/to/file')
  .expect(200)
  .end((err, res) => {
    if (err) throw err;
  });
💻

Example

This example shows a complete Express app with multer handling file uploads and a test using supertest to upload a sample file. The test checks that the server responds with status 200 and confirms the file was received.

javascript
const express = require('express');
const multer = require('multer');
const request = require('supertest');
const path = require('path');

const upload = multer({ dest: 'uploads/' });
const app = express();

app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ message: 'No file uploaded' });
  }
  res.status(200).json({ message: 'File uploaded', filename: req.file.originalname });
});

// Test
(async () => {
  const response = await request(app)
    .post('/upload')
    .attach('file', path.join(__dirname, 'testfile.txt'));

  console.log(response.status); // 200
  console.log(response.body); // { message: 'File uploaded', filename: 'testfile.txt' }
})();
Output
200 {"message":"File uploaded","filename":"testfile.txt"}
⚠️

Common Pitfalls

  • Not using multer or missing upload.single('file') middleware causes req.file to be undefined.
  • Incorrect field name in .attach() does not match the middleware field name.
  • Forgetting to provide a real file path in tests leads to errors.
  • Not handling async test code properly can cause tests to pass silently or fail unexpectedly.
javascript
/* Wrong: Missing multer middleware */
app.post('/upload', (req, res) => {
  if (!req.file) return res.status(400).send('No file uploaded');
  res.send('File uploaded');
});

/* Right: Using multer middleware */
app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) return res.status(400).send('No file uploaded');
  res.send('File uploaded');
});
📊

Quick Reference

Tips for testing file uploads in Express:

  • Use multer middleware to parse files.
  • Use supertest with .attach() to send files in tests.
  • Match the field name in upload.single('fieldName') and .attach('fieldName', filePath).
  • Ensure test files exist and paths are correct.
  • Handle async tests with async/await or callbacks.

Key Takeaways

Use multer middleware in Express to handle file uploads before testing.
Test file uploads with supertest's .attach() method matching the middleware field name.
Always provide a valid file path in tests to avoid errors.
Handle asynchronous test code properly to ensure reliable test results.
Check for req.file existence in your route to confirm file upload success.