Search code examples
javascriptnode.jskoasupertestkoa-router

Content-type header is always the same while testing koa routes with supertest


I have an application build with koa and koa-router. When testing routes with supertest I face a problem, that content-type response header is always application/json; charset=utf-8.

const app = koa();
router
    .get('/img', function *(next) {
      this.type = 'image/png';
      // this.set('Content-Type', 'image/png'); 
      // this.set('content-type', 'image/png');
      this.body = renderImage();
    });

app
  .use(router.routes())
  .use(router.allowedMethods());


describe('Routes', () => {

  it('should handle /tiles/*/*/*/* requests', (done) => {
    request(http.createServer(app.callback()))
      .get('/img')
      .expect(200)
      .expect('Content-Type', 'image/png')
      .end(function (err, res) {
        console.log(res.res.headers);
        if (err) return done(err);

        expect(renderImage).to.be.called;
        done();
      });
  });

How test fails:

Error: expected "Content-Type" of "image/png", got "application/json; charset=utf-8" at Test._assertHeader (node_modules/supertest/lib/test.js:215:12) at Test._assertFunction (node_modules/supertest/lib/test.js:247:11) at Test.assert (node_modules/supertest/lib/test.js:148:18) at Server.assert (node_modules/supertest/lib/test.js:127:12) at emitCloseNT (net.js:1525:8)

What is logged via console.log(res.res.headers):

{ 'content-type': 'application/json; charset=utf-8',
'content-length': '2',
date: 'Wed, 09 Mar 2016 10:15:37 GMT',
connection: 'close' }

Yet, if I do a request from the browser to the provided route, content-type header is changed correctly:

Connection:keep-alive
Content-Length:334
Content-Type:image/png
Date:Wed, 09 Mar 2016 10:15:01 GMT

Neither this.set('Content-Type', 'image/png'); nor this.set('content-type', 'image/png'); changes the situation.

Is it a bug? Has anyone faced the same issue?


Solution

  • A couple things to try:

    Is this.body = renderImage() actually setting the body to null or undefined?
    When looking through the Koa.js code for the response object, it looks like koa is removing the content-type header if the body is set to null or undefined.

    Is the return value of renderImage() an object? If so, is it a buffer or stream? When the body is set koa tries to detect what the content-typeof the response should be. If it is not a string, Buffer, or stream, koa forces the content-type header to be application/json.