8
votes

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.

1
Did u ever get an answer to this ? or any workaround you found out ?Jaspreet Singh
same, did you ever figure this out? working on it nowthehme

1 Answers

1
votes

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();
        });
});