Reputation: 897
I'm using node-mocks-http to test my API and I have problems simulating a file upload. Here is my attempt:
var response = buildResponse()
var request = http_mocks.createRequest({
method: 'POST',
url : '/test',
headers: {
'Content-Type' : 'multipart/form-data;',
'Transfer-Encoding': 'identity'
},
files: {
project: fs.createReadStream('tests/fixtures/test.json')
}
})
response.on('end', function() {
response._getData().should.equal('finished');
done();
})
app.handle(request, response)
Any idea why that wouldn't lead to a proper file upload? At least, the express-fileupload module is not seeing it as one.
Many thanks.
Upvotes: 3
Views: 4061
Reputation: 30219
I'm not directly addressing node-mocks-http
, but I use supertest
to mock file uploads in Node.js testing to achieve the same goal.
In my case, my Express middleware use Formidable to parse form data, especially file uploads; supertest
works really well with Formidable
.
Below is a piece of code sample. It tests my Express middleware, which uploads a file to an Minio S3 bucket.
it('posts a file', done => {
const app = express()
app.post(
'/api/upload',
minioMiddleware({ op: expressMinio.Ops.post }),
(req, res) => {
if (req.minio.error) {
res.status(400).json({ error: req.minio.error })
} else {
res.send(`${req.minio.post.filename}`)
}
}
)
request(app)
.post('/api/upload')
.attach('file', '/tmp/a-file-to-upload.txt')
.expect(200, done)
})
supertest
in this test will upload the file /tmp/a-file-to-upload.txt
and the Middleware will in turn put the file in Minio S3. It works well for me.
Upvotes: 1