Skip to content

Commit

Permalink
fix: check existence of res.getHeader and set the correct Content-T…
Browse files Browse the repository at this point in the history
…ype (#385)
  • Loading branch information
ulivz authored and evilebottnawi committed Apr 3, 2019
1 parent eb2e32b commit 56dc705
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/middleware.js
Expand Up @@ -103,7 +103,7 @@ module.exports = function wrapper(context) {
contentType += '; charset=UTF-8';
}

if (!res.getHeader('Content-Type')) {
if (!res.getHeader || !res.getHeader('Content-Type')) {
res.setHeader('Content-Type', contentType);
}

Expand Down
42 changes: 42 additions & 0 deletions test/mock-express/index.js
@@ -0,0 +1,42 @@
'use strict';

const mockRequest = (options = {}) =>
Object.assign(
{
body: {},
cookies: {},
query: {},
params: {},
get: jest.fn(),
},
options
);

const mockResponse = (options = {}) => {
const res = Object.assign(
{
cookie: jest.fn(),
clearCookie: jest.fn(),
download: jest.fn(),
format: jest.fn(),
json: jest.fn(),
jsonp: jest.fn(),
send: jest.fn(),
sendFile: jest.fn(),
sendStatus: jest.fn(),
setHeader: jest.fn(),
redirect: jest.fn(),
render: jest.fn(),
end: jest.fn(),
set: jest.fn(),
type: jest.fn(),
get: jest.fn(),
},
options
);
res.status = jest.fn(() => res);
res.vary = jest.fn(() => res);
return res;
};

module.exports = { mockRequest, mockResponse };
31 changes: 31 additions & 0 deletions test/server.test.js
Expand Up @@ -9,6 +9,8 @@ const request = require('supertest');

const middleware = require('../');

const { mockRequest, mockResponse } = require('./mock-express');

const webpackConfig = require('./fixtures/server-test/webpack.config');
const webpackMultiConfig = require('./fixtures/server-test/webpack.array.config');
const webpackQuerystringConfig = require('./fixtures/server-test/webpack.querystring.config');
Expand Down Expand Up @@ -311,6 +313,35 @@ describe('Server', () => {
});
});

/**
* ref: #385, for that koa-webpack@4.x doesn't pass in res.getHeader method.
*/
describe('Should work when res.getHeader is undefined', () => {
it('should not throw error', (done) => {
const req = mockRequest({
url: '/',
method: 'GET',
headers: {
Range: 'bytes=6000-',
},
});

const res = mockResponse({
getHeader: undefined,
setHeader: jest.fn(),
});

const compiler = webpack(webpackConfig);
instance = middleware(compiler, {
stats: 'errors-only',
logLevel,
});

instance(req, res, jest.fn()).then(done);
});
afterAll(close);
});

describe('custom mimeTypes', () => {
beforeAll((done) => {
app = express();
Expand Down

0 comments on commit 56dc705

Please sign in to comment.