Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid superagent: double callback bug

I make simple get request using supertest. Response might be an image.

Supertest - v3.0.0
SuperAgent - v3.8.2
Node - carbon (8.9.4)

After all these upgrades, I encountered the following

code:

const request = require('supertest');

it('mocha test', async () => {
  const res = await request('${serviceUrl}').get('/api/image.png')
});

After this request I receive warn superagent: double callback bug and error:

Error: Parse Error
      at Socket.socketOnData (_http_client.js:440:20)
      at addChunk (_stream_readable.js:263:12)
      at readableAddChunk (_stream_readable.js:250:11)
      at Socket.Readable.push (_stream_readable.js:208:10)
      at TCP.onread (net.js:594:20)

I have already read a lot of issues with solution to update superagent to latest version. Does't work for me.

like image 373
Mykola Svyshch Avatar asked Sep 04 '26 07:09

Mykola Svyshch


1 Answers

You are fetching an image, you'll need a parser for getting image. You can try something like this.

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

// example mocha test
it('mocha test', function (done) => {
    request(app)
        .get('/api/image.png')
        .expect(200)
        .expect('Content-Type', 'image.png')
        .buffer()
        .parse(binaryParser)
        .end(function(err, res) {
            if (err) return done(err);

            // binary response data is in res.body as a buffer
            assert.ok(Buffer.isBuffer(res.body));
            console.log("res=", res.body);

            done();
        });
});
like image 54
Faizuddin Mohammed Avatar answered Sep 05 '26 21:09

Faizuddin Mohammed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!