Take a look at the .field() method signature:
field(name: string, val: MultipartValue): this;
field(fields: { [fieldName: string]: MultipartValue }): this;
And MultipartValue type:
type MultipartValueSingle = Blob | Buffer | fs.ReadStream | string | boolean | number;
type MultipartValue = MultipartValueSingle | MultipartValueSingle[];
The value of the field should be Blob | Buffer | fs.ReadStream | string | boolean | number;. It doesn't accept objects.
So you need to use JSON.stringify(contact).
E.g.
app.js:
const express = require('express');
const multer = require('multer');
const path = require('path');
const upload = multer({ dest: path.resolve(__dirname, 'uploads/') });
const app = express();
app.post('/profile', upload.single('logo'), (req, res) => {
console.log(req.body);
console.log(req.file);
const profile = { email: req.body.email, logo: true };
res.json({ status: 'created', profile });
});
module.exports = app;
app.test.js:
const server = require('./app');
const chai = require('chai');
const path = require('path');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
describe('66273169', () => {
it('should pass', async () => {
const email = 'test.email@gmail.com';
const contact = {
firstName: 'John',
lastName: 'Doe',
phone: '9876543212',
};
const response = await chai
.request(server)
.post('/profile')
.set('Content-Type', 'multipart/form-data')
.attach('logo', path.resolve(__dirname, 'logo.png'))
.field({
email,
name: 'All Tech Solutions',
phone: '9812345678',
contact: JSON.stringify(contact),
});
expect(response.body.status).to.equal('created');
expect(response.body.profile.email).to.equal(email);
expect(response.body.profile.logo).to.exist;
});
});
test result:
66273169
[Object: null prototype] {
email: 'test.email@gmail.com',
name: 'All Tech Solutions',
phone: '9812345678',
contact: '{"firstName":"John","lastName":"Doe","phone":"9876543212"}'
}
{
fieldname: 'logo',
originalname: 'logo.png',
encoding: '7bit',
mimetype: 'image/png',
destination: '/Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/66273169/uploads',
filename: '7b82676df1678c79da43abcfbd9d411f',
path: '/Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/66273169/uploads/7b82676df1678c79da43abcfbd9d411f',
size: 0
}
✓ should pass
1 passing (31ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
app.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------