我有一个使用 koa
和 koa-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 设置为 null
或 undefined
?
当查看 Koa.js 代码时发现 response object ,如果主体设置为 null
或 undefined
,则 koa 似乎正在删除 content-type
header 。
renderImage()的返回值是一个对象吗?如果是,它是缓冲区还是流?当 body
设置时,koa 会尝试检测响应的内容类型应该是什么。如果它不是 string
、Buffer
或 stream
,则 koa forces content-type
header 为 application/json
。
关于javascript - 使用 supertest 测试 koa 路由时,内容类型 header 始终相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35888992/