Reputation: 953
I am trying to test the post request using mocha, and the post request body contains an image field along with the json data. The test is not executing when the image is attached along with the json. And test is executing but raising 400 error without the attachment. Attaching my code here.
var request = require('supertest');
var app = require('../server')
request(app).post('/companies/')
.set({apikey: 'TestHashKey',
'app-token': process.env.API_TOKEN,
'app-key': process.env.API_KEY})
.field('Content-Type', 'multipart/form-data')
.field('name', 'sample_companyx')
.field('phoneNumber','+963014311354')
.attach('logo', '/app/test/images/test_logo.jpg')
.expect(200)
.end(function (err, res) {
if (err) {
throw err;
}
done();
});
And the response without attachment is pasting below,
POST /companies/ 400 12ms - 12b response Missing logo 2016-01-22T04:08:20.044Z - error: Fri, 22 Jan 2016 04:08:20 GMT uncaughtException: expected 200 "OK", got 400 "Bad Request"
The response whilst the attachment exist is
2016-01-22T04:13:44.849Z - info: [beta] Companies API up and running on port 4000 2016-01-22T04:13:45.916Z - info: Companies worker ready! npm ERR! Test failed. See above for more details. npm ERR! not ok code 0
Upvotes: 2
Views: 5326
Reputation: 543
The solution above (while helpful to look at) did not work for me as req.file or req.files did not hold any info when replicating solution.
If someone is still looking for a solution, I used "form.parse" as part of multiparty library on my backend (nodejs) to get the files object from req, in which took me forever to realize that the file was stored on the attachment field on "files" as you can see below.
exports.nodeFunction = function (req, res) {
var form = new multiparty.Form({
uploadDir: 'app/tmp'
});
form.parse(req, function (err, fields, files) { //https://www.npmjs.com/package/multiparty
var file = files.file ? files.file[0] : files.attachment[0];
// when uploaded on front end, files.file has the file, but files.attachment holds the file when using supertest in mocha.
});
Here's my test function as well:
describe('POST', function () {
it('Should upload file', async function () {
const res = await request(app).post(url) // request = require('supertest')
.attach('attachment', path.resolve(__dirname, filename)) // using "path" library
.expect(200)
});
});
Upvotes: 0
Reputation: 102207
Here is a minimal working example:
app.js
:
const express = require("express");
const multer = require("multer");
const path = require("path");
const crypto = require("crypto");
const app = express();
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, path.resolve(__dirname, "uploads/"));
},
filename: function(req, file, cb) {
crypto.pseudoRandomBytes(16, function(err, raw) {
if (err) return cb(err);
cb(null, raw.toString("hex") + path.extname(file.originalname));
});
},
});
const upload = multer({ storage });
app.post("/companies/", upload.single("logo"), (req, res) => {
console.log("req.body: ", req.body);
console.log("req.file:", req.file);
res.sendStatus(200);
});
module.exports = app;
app.test.js
:
const app = require("./app");
const request = require("supertest");
const path = require("path");
describe("34939199", () => {
it("should pass", (done) => {
process.env.API_TOKEN = "123";
process.env.API_KEY = "abc";
request(app)
.post("/companies/")
.set({ apikey: "TestHashKey", "app-token": process.env.API_TOKEN, "app-key": process.env.API_KEY })
.field("Content-Type", "multipart/form-data")
.field("name", "sample_companyx")
.field("phoneNumber", "+963014311354")
.attach("logo", path.resolve(__dirname, "fixtures/test_logo.jpg"))
.expect(200)
.end(function(err, res) {
if (err) {
throw err;
}
done();
});
});
});
Integration test result with coverage report:
34939199
req.body: [Object: null prototype] {
'Content-Type': 'multipart/form-data',
name: 'sample_companyx',
phoneNumber: '+963014311354' }
req.file: { fieldname: 'logo',
originalname: 'test_logo.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination:
'/Users/ldu020/workspace/github.com/mrdulin/mocha-chai-sinon-codelab/src/stackoverflow/34939199/uploads',
filename: 'da39e06c1cd2a97f98a66eb6d832aa74.jpg',
path:
'/Users/ldu020/workspace/github.com/mrdulin/mocha-chai-sinon-codelab/src/stackoverflow/34939199/uploads/da39e06c1cd2a97f98a66eb6d832aa74.jpg',
size: 0 }
✓ should pass (50ms)
1 passing (56ms)
-------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files | 93.1 | 50 | 100 | 96.43 | |
app.js | 94.12 | 50 | 100 | 100 | 13 |
app.test.js | 91.67 | 50 | 100 | 91.67 | 20 |
-------------|----------|----------|----------|----------|-------------------|
Folder structure:
.
├── app.js
├── app.test.js
├── fixtures
│ └── test_logo.jpg
└── uploads
└── da39e06c1cd2a97f98a66eb6d832aa74.jpg
2 directories, 4 files
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/34939199
Upvotes: 1