1 year ago

#187949

test-img

Miguel V

How can I test an endpoint that has downloadable content using sinon?

I have the following segment of code:

        it('Should return a csv document', function (done) {
            const findOneFake = sinon.fake.resolves(dummyIndicador);
            sinon.replace(Indicador, 'findOne', findOneFake);
            chai.request(app)
                .get('/api/v1/documentos/1/csv')
                .end(function (err, res) {  
                    expect(findOneFake.calledOnce).to.be.true;
                    expect(res).to.have.status(200);
                    expect(res.headers['content-type']).to.be.equal('application/csv');
                    expect(res.headers['content-disposition']).to.have.string('attachment');
                    done();
                });
        });

This endpoint will run the following service:

const generateCSV = (res, data) => {
  data = data.dataValues;
  const json2csv = new Parser();
  const csv = json2csv.parse(data);
        return (
        res.header('Content-disposition', 'attachment'),
        res.header('Content-Type', 'application/csv'),
        res.attachment(`${data.nombre}.csv`),
        res.send(csv));
};

This returns an csv file when accessing baseURL/api/v1/documentos/id/csv. I was expecting to evaluate the response headers in order to verify that it has the value of "application/csv" and the 'attachment' attribute on them to test if its retrieving them correctly, but when I run the test I obtain the following error:

 Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (src\test\controllers\indicadorControllerTest.js)
  at listOnTimeout (internal/timers.js:554:17)
  at processTimers (internal/timers.js:497:7)

I have already tried to do increase the timeout, but it stays loading forever. I think that this error is happening because it is delivering the file but it doesn't have a way to handle it, and I don't know how to do this (if this is indeed the reason)

node.js

express

testing

sinon

sinon-chai

0 Answers

Your Answer

Accepted video resources