Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to functional/unit test files downloaded with Node.js + Express.js

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.

like image 812
nikjohn Avatar asked May 29 '16 20:05

nikjohn


1 Answers

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();
        });
});
like image 120
thehme Avatar answered Oct 29 '22 00:10

thehme