In my Node.js, Express.js application, I have an API that I consume to convert to a CSV file and subsequently download it on the client like so:
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment; filename=BuyNowOrders.csv;');
res.end(csv, 'binary');
I have Mocha/Sinon/Nighwatch.js test suite that I use for unit testing as well as functional testing with a full-fledged mock-api
server module that serves up mock data.
How do I test this functionality? Normally I do functional testing and unit testing for each module.
I have so far written tests for the Download button to be present on the page, but I'm not sure how to test whether the file has been downloaded.
This is how I did it, considering my file is being returned as an encoded attachment from the endpoint that was being functionally tested.
function binaryParser(res, callback) {
res.setEncoding('binary');
res.data = '';
res.on('data', function (chunk) {
res.data += chunk;
});
res.on('end', function () {
callback(null, new Buffer(res.data, 'binary'));
});
}
it("returns success response (200) and attachment file when downloading data file", (done) => {
request
.get('/download/XXXXX/data')
.expect(200)
.expect('Content-Type', 'application/json; charset=utf-8') // encoded content
.buffer()
.parse(binaryParser)
.end((err, res) => {
if (err) {
return done(err);
}
assert.ok(Buffer.isBuffer(res.body));
console.log("res=", res.body);
done();
});
});
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