javascript - 使用 supertest 测试 koa 路由时,内容类型 header 始终相同

标签 javascript node.js koa supertest koa-router

我有一个使用 koakoa-router 构建的应用程序。当使用 supertest 测试路由时,我遇到一个问题,content-type 响应 header 始终是 application/json;字符集=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();
      });
  });

测试如何失败:

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)

通过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' }

但是,如果我从浏览器向提供的路由发出请求,则 content-type header 会正确更改:

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

既不是 this.set('Content-Type', 'image/png'); 也不是 this.set('content-type', 'image/png'); 改变了情况。

这是一个错误吗?有人遇到过同样的问题吗?

最佳答案

有几件事需要尝试:

this.body = renderImage() 是否真的将 body 设置为 nullundefined
当查看 Koa.js 代码时发现 response object ,如果主体设置为 nullundefined,则 koa 似乎正在删除 content-type header 。

renderImage()的返回值是一个对象吗?如果是,它是缓冲区还是流?当 body 设置时,koa 会尝试检测响应的内容类型应该是什么。如果它不是 stringBufferstream,则 koa forces content-type header 为 application/json

关于javascript - 使用 supertest 测试 koa 路由时,内容类型 header 始终相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35888992/

相关文章:

javascript - Laravel - 让 vue 与其他插件一起工作

javascript - 在javascript中使用innerHTML编写函数

javascript - 电话间隙 : Back button not working

javascript - 使用 Node js 连接到 postgres

javascript - Nodejs : . then() 语句在 Promise.all() 之后不执行

javascript - 在 koajs 中重定向之前等待异步进程完成

php - 为什么这个 JQuery/AJAX 调用不起作用?

javascript - 关于在 AWS NodeJS 上使用 TypeScript。 (获取 TS 而不是 JS 的堆栈跟踪)

jwt - 如何获得正确的 Auth0 不记名 token ?

javascript - 如何在 Koa/Express 的每条路线(网页)上共享全局侧边栏/页脚?