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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With