From c6082de06ebfa15ec0a5acfb2ed5e864534a59b7 Mon Sep 17 00:00:00 2001 From: Monaam Aouini Date: Thu, 31 Oct 2024 10:30:51 +0100 Subject: [PATCH 1/2] style: format code with prettier --- .github/workflows/ci.yml | 2 + .prettierignore | 1 + .prettierrc | 9 + benchmarks/middleware.js | 7 +- examples/auth/index.js | 64 +- examples/content-negotiation/db.js | 2 +- examples/content-negotiation/index.js | 38 +- examples/content-negotiation/users.js | 30 +- examples/cookie-sessions/index.js | 10 +- examples/cookies/index.js | 24 +- examples/downloads/index.js | 22 +- examples/ejs/index.js | 12 +- examples/error-pages/index.js | 30 +- examples/error/index.js | 10 +- examples/hello-world/index.js | 6 +- examples/markdown/index.js | 14 +- examples/multi-router/controllers/api_v1.js | 6 +- examples/multi-router/controllers/api_v2.js | 6 +- examples/multi-router/index.js | 8 +- examples/mvc/controllers/main/index.js | 4 +- examples/mvc/controllers/pet/index.js | 10 +- examples/mvc/controllers/user-pet/index.js | 4 +- examples/mvc/controllers/user/index.js | 14 +- examples/mvc/db.js | 8 +- examples/mvc/index.js | 28 +- examples/mvc/lib/boot.js | 19 +- examples/online/index.js | 20 +- examples/params/index.js | 32 +- examples/resource/index.js | 67 +- examples/route-map/index.js | 45 +- examples/route-middleware/index.js | 27 +- examples/route-separation/index.js | 4 +- examples/route-separation/post.js | 6 +- examples/route-separation/site.js | 4 +- examples/route-separation/user.js | 18 +- examples/search/index.js | 8 +- examples/search/public/client.js | 26 +- examples/session/index.js | 20 +- examples/session/redis.js | 24 +- examples/static-files/index.js | 2 +- examples/vhost/index.js | 10 +- examples/view-constructor/github-view.js | 28 +- examples/view-constructor/index.js | 14 +- examples/view-locals/index.js | 40 +- examples/view-locals/user.js | 10 +- examples/web-service/index.js | 30 +- lib/application.js | 91 +- lib/express.js | 20 +- lib/request.js | 78 +- lib/response.js | 242 ++-- lib/utils.js | 55 +- lib/view.js | 21 +- package.json | 2 + test/Route.js | 192 ++-- test/Router.js | 447 ++++---- test/acceptance/auth.js | 164 ++- test/acceptance/content-negotiation.js | 73 +- test/acceptance/cookie-sessions.js | 47 +- test/acceptance/cookies.js | 115 +- test/acceptance/downloads.js | 61 +- test/acceptance/ejs.js | 29 +- test/acceptance/error-pages.js | 154 ++- test/acceptance/error.js | 45 +- test/acceptance/hello-world.js | 23 +- test/acceptance/markdown.js | 31 +- test/acceptance/multi-router.js | 68 +- test/acceptance/mvc.js | 208 ++-- test/acceptance/params.js | 66 +- test/acceptance/resource.js | 98 +- test/acceptance/route-map.js | 69 +- test/acceptance/route-separation.js | 113 +- test/acceptance/vhost.js | 76 +- test/acceptance/web-service.js | 165 ++- test/app.all.js | 42 +- test/app.engine.js | 74 +- test/app.head.js | 71 +- test/app.js | 142 ++- test/app.listen.js | 34 +- test/app.locals.js | 38 +- test/app.options.js | 117 +- test/app.param.js | 212 ++-- test/app.render.js | 344 +++--- test/app.request.js | 156 ++- test/app.response.js | 156 ++- test/app.route.js | 245 ++-- test/app.router.js | 1117 +++++++++---------- test/app.routes.error.js | 90 +- test/app.use.js | 382 +++---- test/config.js | 190 ++-- test/exports.js | 116 +- test/express.json.js | 844 ++++++++------ test/express.raw.js | 663 ++++++----- test/express.static.js | 706 ++++++------ test/express.text.js | 669 ++++++----- test/express.urlencoded.js | 853 +++++++------- test/middleware.basic.js | 46 +- test/regression.js | 21 +- test/req.accepts.js | 123 +- test/req.acceptsCharsets.js | 52 +- test/req.acceptsEncodings.js | 34 +- test/req.acceptsLanguages.js | 50 +- test/req.baseUrl.js | 142 ++- test/req.fresh.js | 66 +- test/req.get.js | 64 +- test/req.host.js | 145 ++- test/req.hostname.js | 190 ++-- test/req.ip.js | 98 +- test/req.ips.js | 76 +- test/req.is.js | 205 ++-- test/req.path.js | 24 +- test/req.protocol.js | 98 +- test/req.query.js | 58 +- test/req.range.js | 122 +- test/req.route.js | 28 +- test/req.secure.js | 96 +- test/req.signedCookies.js | 41 +- test/req.stale.js | 49 +- test/req.subdomains.js | 169 ++- test/req.xhr.js | 48 +- test/res.append.js | 123 +- test/res.attachment.js | 89 +- test/res.clearCookie.js | 80 +- test/res.cookie.js | 269 ++--- test/res.download.js | 450 ++++---- test/res.format.js | 303 ++--- test/res.get.js | 16 +- test/res.json.js | 188 ++-- test/res.jsonp.js | 314 +++--- test/res.links.js | 38 +- test/res.locals.js | 40 +- test/res.location.js | 224 ++-- test/res.redirect.js | 254 +++-- test/res.render.js | 306 +++-- test/res.send.js | 446 ++++---- test/res.sendFile.js | 760 ++++++------- test/res.sendStatus.js | 36 +- test/res.set.js | 112 +- test/res.status.js | 110 +- test/res.type.js | 49 +- test/res.vary.js | 63 +- test/support/env.js | 1 - test/support/tmpl.js | 2 +- test/support/utils.js | 46 +- test/utils.js | 101 +- 144 files changed, 8692 insertions(+), 8610 deletions(-) create mode 100644 .prettierignore create mode 100644 .prettierrc diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5668ed2f22b..913269597bd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,8 @@ jobs: - name: Run lint run: npm run lint + - name: Format code + run: npm run format test: strategy: diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000000..c2658d7d1b3 --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +node_modules/ diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000000..8dfeca65dad --- /dev/null +++ b/.prettierrc @@ -0,0 +1,9 @@ +{ + "trailingComma": "all", + "tabWidth": 2, + "semi": true, + "useTabs": false, + "singleQuote": true, + "printWidth": 80, + "jsxSingleQuote": false +} diff --git a/benchmarks/middleware.js b/benchmarks/middleware.js index fed97ba8ce4..8d61386e005 100644 --- a/benchmarks/middleware.js +++ b/benchmarks/middleware.js @@ -1,4 +1,3 @@ - var express = require('..'); var app = express(); @@ -8,13 +7,13 @@ var n = parseInt(process.env.MW || '1', 10); console.log(' %s middleware', n); while (n--) { - app.use(function(req, res, next){ + app.use(function (req, res, next) { next(); }); } -app.use(function(req, res){ - res.send('Hello World') +app.use(function (req, res) { + res.send('Hello World'); }); app.listen(3333); diff --git a/examples/auth/index.js b/examples/auth/index.js index 2884ca4e170..eadcba1411d 100644 --- a/examples/auth/index.js +++ b/examples/auth/index.js @@ -1,15 +1,15 @@ -'use strict' +'use strict'; /** * Module dependencies. */ var express = require('../..'); -var hash = require('pbkdf2-password')() +var hash = require('pbkdf2-password')(); var path = require('path'); var session = require('express-session'); -var app = module.exports = express(); +var app = (module.exports = express()); // config @@ -18,16 +18,18 @@ app.set('views', path.join(__dirname, 'views')); // middleware -app.use(express.urlencoded()) -app.use(session({ - resave: false, // don't save session if unmodified - saveUninitialized: false, // don't create session until something stored - secret: 'shhhh, very secret' -})); +app.use(express.urlencoded()); +app.use( + session({ + resave: false, // don't save session if unmodified + saveUninitialized: false, // don't create session until something stored + secret: 'shhhh, very secret', + }), +); // Session-persisted message middleware -app.use(function(req, res, next){ +app.use(function (req, res, next) { var err = req.session.error; var msg = req.session.success; delete req.session.error; @@ -41,7 +43,7 @@ app.use(function(req, res, next){ // dummy database var users = { - tj: { name: 'tj' } + tj: { name: 'tj' }, }; // when you create a user, generate a salt @@ -54,21 +56,20 @@ hash({ password: 'foobar' }, function (err, pass, salt, hash) { users.tj.hash = hash; }); - // Authenticate using our plain-object database of doom! function authenticate(name, pass, fn) { if (!module.parent) console.log('authenticating %s:%s', name, pass); var user = users[name]; // query the db for the given username - if (!user) return fn(null, null) + if (!user) return fn(null, null); // apply the same algorithm to the POSTed password, applying // the hash against the pass / salt, if there is a match we // found the user hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) { if (err) return fn(err); - if (hash === user.hash) return fn(null, user) - fn(null, null) + if (hash === user.hash) return fn(null, user); + fn(null, null); }); } @@ -81,47 +82,50 @@ function restrict(req, res, next) { } } -app.get('/', function(req, res){ +app.get('/', function (req, res) { res.redirect('/login'); }); -app.get('/restricted', restrict, function(req, res){ +app.get('/restricted', restrict, function (req, res) { res.send('Wahoo! restricted area, click to logout'); }); -app.get('/logout', function(req, res){ +app.get('/logout', function (req, res) { // destroy the user's session to log them out // will be re-created next request - req.session.destroy(function(){ + req.session.destroy(function () { res.redirect('/'); }); }); -app.get('/login', function(req, res){ +app.get('/login', function (req, res) { res.render('login'); }); app.post('/login', function (req, res, next) { - if (!req.body) return res.sendStatus(400) - authenticate(req.body.username, req.body.password, function(err, user){ - if (err) return next(err) + if (!req.body) return res.sendStatus(400); + authenticate(req.body.username, req.body.password, function (err, user) { + if (err) return next(err); if (user) { // Regenerate session when signing in // to prevent fixation - req.session.regenerate(function(){ + req.session.regenerate(function () { // Store the user's primary key // in the session store to be retrieved, // or in this case the entire user object req.session.user = user; - req.session.success = 'Authenticated as ' + user.name - + ' click to logout. ' - + ' You may now access /restricted.'; + req.session.success = + 'Authenticated as ' + + user.name + + ' click to logout. ' + + ' You may now access /restricted.'; res.redirect(req.get('Referrer') || '/'); }); } else { - req.session.error = 'Authentication failed, please check your ' - + ' username and password.' - + ' (use "tj" and "foobar")'; + req.session.error = + 'Authentication failed, please check your ' + + ' username and password.' + + ' (use "tj" and "foobar")'; res.redirect('/login'); } }); diff --git a/examples/content-negotiation/db.js b/examples/content-negotiation/db.js index f59b23bf18e..1db9ac1ff8a 100644 --- a/examples/content-negotiation/db.js +++ b/examples/content-negotiation/db.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; var users = []; diff --git a/examples/content-negotiation/index.js b/examples/content-negotiation/index.js index 280a4e22998..f8cb4d14765 100644 --- a/examples/content-negotiation/index.js +++ b/examples/content-negotiation/index.js @@ -1,28 +1,38 @@ -'use strict' +'use strict'; var express = require('../../'); -var app = module.exports = express(); +var app = (module.exports = express()); var users = require('./db'); // so either you can deal with different types of formatting // for expected response in index.js -app.get('/', function(req, res){ +app.get('/', function (req, res) { res.format({ - html: function(){ - res.send(''); + html: function () { + res.send( + '', + ); }, - text: function(){ - res.send(users.map(function(user){ - return ' - ' + user.name + '\n'; - }).join('')); + text: function () { + res.send( + users + .map(function (user) { + return ' - ' + user.name + '\n'; + }) + .join(''), + ); }, - json: function(){ + json: function () { res.json(users); - } + }, }); }); @@ -32,7 +42,7 @@ app.get('/', function(req, res){ function format(path) { var obj = require(path); - return function(req, res){ + return function (req, res) { res.format(obj); }; } diff --git a/examples/content-negotiation/users.js b/examples/content-negotiation/users.js index fe703e73a9a..f4f75c4fd35 100644 --- a/examples/content-negotiation/users.js +++ b/examples/content-negotiation/users.js @@ -1,19 +1,29 @@ -'use strict' +'use strict'; var users = require('./db'); -exports.html = function(req, res){ - res.send(''); +exports.html = function (req, res) { + res.send( + '', + ); }; -exports.text = function(req, res){ - res.send(users.map(function(user){ - return ' - ' + user.name + '\n'; - }).join('')); +exports.text = function (req, res) { + res.send( + users + .map(function (user) { + return ' - ' + user.name + '\n'; + }) + .join(''), + ); }; -exports.json = function(req, res){ +exports.json = function (req, res) { res.json(users); }; diff --git a/examples/cookie-sessions/index.js b/examples/cookie-sessions/index.js index 83b6faee82b..f9b7df433e5 100644 --- a/examples/cookie-sessions/index.js +++ b/examples/cookie-sessions/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -7,16 +7,16 @@ var cookieSession = require('cookie-session'); var express = require('../../'); -var app = module.exports = express(); +var app = (module.exports = express()); // add req.session cookie support app.use(cookieSession({ secret: 'manny is cool' })); // do something with the session app.get('/', function (req, res) { - req.session.count = (req.session.count || 0) + 1 - res.send('viewed ' + req.session.count + ' times\n') -}) + req.session.count = (req.session.count || 0) + 1; + res.send('viewed ' + req.session.count + ' times\n'); +}); /* istanbul ignore next */ if (!module.parent) { diff --git a/examples/cookies/index.js b/examples/cookies/index.js index 0620cb40e45..074b7f6796f 100644 --- a/examples/cookies/index.js +++ b/examples/cookies/index.js @@ -1,16 +1,16 @@ -'use strict' +'use strict'; /** * Module dependencies. */ var express = require('../../'); -var app = module.exports = express(); +var app = (module.exports = express()); var logger = require('morgan'); var cookieParser = require('cookie-parser'); // custom log format -if (process.env.NODE_ENV !== 'test') app.use(logger(':method :url')) +if (process.env.NODE_ENV !== 'test') app.use(logger(':method :url')); // parses request cookies, populating // req.cookies and req.signedCookies @@ -19,28 +19,30 @@ if (process.env.NODE_ENV !== 'test') app.use(logger(':method :url')) app.use(cookieParser('my secret here')); // parses x-www-form-urlencoded -app.use(express.urlencoded()) +app.use(express.urlencoded()); -app.get('/', function(req, res){ +app.get('/', function (req, res) { if (req.cookies.remember) { res.send('Remembered :). Click to forget!.'); } else { - res.send('

Check to ' - + '.

'); + res.send( + '

Check to ' + + '.

', + ); } }); -app.get('/forget', function(req, res){ +app.get('/forget', function (req, res) { res.clearCookie('remember'); res.redirect(req.get('Referrer') || '/'); }); -app.post('/', function(req, res){ +app.post('/', function (req, res) { var minute = 60000; if (req.body && req.body.remember) { - res.cookie('remember', 1, { maxAge: minute }) + res.cookie('remember', 1, { maxAge: minute }); } res.redirect(req.get('Referrer') || '/'); diff --git a/examples/downloads/index.js b/examples/downloads/index.js index c47dddd738a..2f771c57914 100644 --- a/examples/downloads/index.js +++ b/examples/downloads/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -7,18 +7,20 @@ var express = require('../../'); var path = require('path'); -var app = module.exports = express(); +var app = (module.exports = express()); // path to where the files are stored on disk -var FILES_DIR = path.join(__dirname, 'files') +var FILES_DIR = path.join(__dirname, 'files'); -app.get('/', function(req, res){ - res.send('') +app.get('/', function (req, res) { + res.send( + '', + ); }); // /files/* is accessed via req.params[0] diff --git a/examples/ejs/index.js b/examples/ejs/index.js index a39d805a160..4dde6cb0703 100644 --- a/examples/ejs/index.js +++ b/examples/ejs/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -7,7 +7,7 @@ var express = require('../../'); var path = require('path'); -var app = module.exports = express(); +var app = (module.exports = express()); // Register ejs as .html. If we did // not call this, we would need to @@ -39,14 +39,14 @@ app.set('view engine', 'html'); var users = [ { name: 'tobi', email: 'tobi@learnboost.com' }, { name: 'loki', email: 'loki@learnboost.com' }, - { name: 'jane', email: 'jane@learnboost.com' } + { name: 'jane', email: 'jane@learnboost.com' }, ]; -app.get('/', function(req, res){ +app.get('/', function (req, res) { res.render('users', { users: users, - title: "EJS example", - header: "Some users" + title: 'EJS example', + header: 'Some users', }); }); diff --git a/examples/error-pages/index.js b/examples/error-pages/index.js index efa815c4740..b472a123cc5 100644 --- a/examples/error-pages/index.js +++ b/examples/error-pages/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -6,9 +6,9 @@ var express = require('../../'); var path = require('path'); -var app = module.exports = express(); +var app = (module.exports = express()); var logger = require('morgan'); -var silent = process.env.NODE_ENV === 'test' +var silent = process.env.NODE_ENV === 'test'; // general config app.set('views', path.join(__dirname, 'views')); @@ -21,31 +21,31 @@ app.enable('verbose errors'); // disable them in production // use $ NODE_ENV=production node examples/error-pages -if (app.settings.env === 'production') app.disable('verbose errors') +if (app.settings.env === 'production') app.disable('verbose errors'); silent || app.use(logger('dev')); // Routes -app.get('/', function(req, res){ +app.get('/', function (req, res) { res.render('index.ejs'); }); -app.get('/404', function(req, res, next){ +app.get('/404', function (req, res, next) { // trigger a 404 since no other middleware // will match /404 after this one, and we're not // responding here next(); }); -app.get('/403', function(req, res, next){ +app.get('/403', function (req, res, next) { // trigger a 403 error var err = new Error('not allowed!'); err.status = 403; next(err); }); -app.get('/500', function(req, res, next){ +app.get('/500', function (req, res, next) { // trigger a generic (500) error next(new Error('keyboard cat!')); }); @@ -60,20 +60,20 @@ app.get('/500', function(req, res, next){ // $ curl http://localhost:3000/notfound -H "Accept: application/json" // $ curl http://localhost:3000/notfound -H "Accept: text/plain" -app.use(function(req, res, next){ +app.use(function (req, res, next) { res.status(404); res.format({ html: function () { - res.render('404', { url: req.url }) + res.render('404', { url: req.url }); }, json: function () { - res.json({ error: 'Not found' }) + res.json({ error: 'Not found' }); }, default: function () { - res.type('txt').send('Not found') - } - }) + res.type('txt').send('Not found'); + }, + }); }); // error-handling middleware, take the same form @@ -88,7 +88,7 @@ app.use(function(req, res, next){ // would remain being executed, however here // we simply respond with an error page. -app.use(function(err, req, res, next){ +app.use(function (err, req, res, next) { // we may use properties of the error object // here and next(err) appropriately, or if // we possibly recovered from the error, simply next(). diff --git a/examples/error/index.js b/examples/error/index.js index d733a81172d..8adfa34d1f2 100644 --- a/examples/error/index.js +++ b/examples/error/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -6,8 +6,8 @@ var express = require('../../'); var logger = require('morgan'); -var app = module.exports = express(); -var test = app.get('env') === 'test' +var app = (module.exports = express()); +var test = app.get('env') === 'test'; if (!test) app.use(logger('dev')); @@ -31,12 +31,12 @@ app.get('/', function () { throw new Error('something broke!'); }); -app.get('/next', function(req, res, next){ +app.get('/next', function (req, res, next) { // We can also pass exceptions to next() // The reason for process.nextTick() is to show that // next() can be called inside an async operation, // in real life it can be a DB read or HTTP request. - process.nextTick(function(){ + process.nextTick(function () { next(new Error('oh no!')); }); }); diff --git a/examples/hello-world/index.js b/examples/hello-world/index.js index 8c1855c2eb7..00c719cfbe1 100644 --- a/examples/hello-world/index.js +++ b/examples/hello-world/index.js @@ -1,10 +1,10 @@ -'use strict' +'use strict'; var express = require('../../'); -var app = module.exports = express() +var app = (module.exports = express()); -app.get('/', function(req, res){ +app.get('/', function (req, res) { res.send('Hello World'); }); diff --git a/examples/markdown/index.js b/examples/markdown/index.js index 23d645e66b2..b140cc21735 100644 --- a/examples/markdown/index.js +++ b/examples/markdown/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -10,14 +10,14 @@ var fs = require('fs'); var marked = require('marked'); var path = require('path'); -var app = module.exports = express(); +var app = (module.exports = express()); // register .md as an engine in express view system -app.engine('md', function(path, options, fn){ - fs.readFile(path, 'utf8', function(err, str){ +app.engine('md', function (path, options, fn) { + fs.readFile(path, 'utf8', function (err, str) { if (err) return fn(err); - var html = marked.parse(str).replace(/\{([^}]+)\}/g, function(_, name){ + var html = marked.parse(str).replace(/\{([^}]+)\}/g, function (_, name) { return escapeHtml(options[name] || ''); }); fn(null, html); @@ -29,11 +29,11 @@ app.set('views', path.join(__dirname, 'views')); // make it the default, so we don't need .md app.set('view engine', 'md'); -app.get('/', function(req, res){ +app.get('/', function (req, res) { res.render('index', { title: 'Markdown Example' }); }); -app.get('/fail', function(req, res){ +app.get('/fail', function (req, res) { res.render('missing', { title: 'Markdown Example' }); }); diff --git a/examples/multi-router/controllers/api_v1.js b/examples/multi-router/controllers/api_v1.js index a301e3ee72d..b2dc37dd152 100644 --- a/examples/multi-router/controllers/api_v1.js +++ b/examples/multi-router/controllers/api_v1.js @@ -1,14 +1,14 @@ -'use strict' +'use strict'; var express = require('../../..'); var apiv1 = express.Router(); -apiv1.get('/', function(req, res) { +apiv1.get('/', function (req, res) { res.send('Hello from APIv1 root route.'); }); -apiv1.get('/users', function(req, res) { +apiv1.get('/users', function (req, res) { res.send('List of APIv1 users.'); }); diff --git a/examples/multi-router/controllers/api_v2.js b/examples/multi-router/controllers/api_v2.js index e997fb1f88c..3f6e46fb79a 100644 --- a/examples/multi-router/controllers/api_v2.js +++ b/examples/multi-router/controllers/api_v2.js @@ -1,14 +1,14 @@ -'use strict' +'use strict'; var express = require('../../..'); var apiv2 = express.Router(); -apiv2.get('/', function(req, res) { +apiv2.get('/', function (req, res) { res.send('Hello from APIv2 root route.'); }); -apiv2.get('/users', function(req, res) { +apiv2.get('/users', function (req, res) { res.send('List of APIv2 users.'); }); diff --git a/examples/multi-router/index.js b/examples/multi-router/index.js index dbfd2841262..de7e8f74d9c 100644 --- a/examples/multi-router/index.js +++ b/examples/multi-router/index.js @@ -1,14 +1,14 @@ -'use strict' +'use strict'; var express = require('../..'); -var app = module.exports = express(); +var app = (module.exports = express()); app.use('/api/v1', require('./controllers/api_v1')); app.use('/api/v2', require('./controllers/api_v2')); -app.get('/', function(req, res) { - res.send('Hello from root route.') +app.get('/', function (req, res) { + res.send('Hello from root route.'); }); /* istanbul ignore next */ diff --git a/examples/mvc/controllers/main/index.js b/examples/mvc/controllers/main/index.js index 74cde191cd8..fd2b1826fda 100644 --- a/examples/mvc/controllers/main/index.js +++ b/examples/mvc/controllers/main/index.js @@ -1,5 +1,5 @@ -'use strict' +'use strict'; -exports.index = function(req, res){ +exports.index = function (req, res) { res.redirect('/users'); }; diff --git a/examples/mvc/controllers/pet/index.js b/examples/mvc/controllers/pet/index.js index 214160f9a46..3d880022dce 100644 --- a/examples/mvc/controllers/pet/index.js +++ b/examples/mvc/controllers/pet/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -8,22 +8,22 @@ var db = require('../../db'); exports.engine = 'ejs'; -exports.before = function(req, res, next){ +exports.before = function (req, res, next) { var pet = db.pets[req.params.pet_id]; if (!pet) return next('route'); req.pet = pet; next(); }; -exports.show = function(req, res, next){ +exports.show = function (req, res, next) { res.render('show', { pet: req.pet }); }; -exports.edit = function(req, res, next){ +exports.edit = function (req, res, next) { res.render('edit', { pet: req.pet }); }; -exports.update = function(req, res, next){ +exports.update = function (req, res, next) { var body = req.body; req.pet.name = body.pet.name; res.message('Information updated!'); diff --git a/examples/mvc/controllers/user-pet/index.js b/examples/mvc/controllers/user-pet/index.js index 42a29adebe7..6abccfc06fe 100644 --- a/examples/mvc/controllers/user-pet/index.js +++ b/examples/mvc/controllers/user-pet/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -9,7 +9,7 @@ var db = require('../../db'); exports.name = 'pet'; exports.prefix = '/user/:user_id'; -exports.create = function(req, res, next){ +exports.create = function (req, res, next) { var id = req.params.user_id; var user = db.users[id]; var body = req.body; diff --git a/examples/mvc/controllers/user/index.js b/examples/mvc/controllers/user/index.js index ec3ae4c8110..9b6ce64bf77 100644 --- a/examples/mvc/controllers/user/index.js +++ b/examples/mvc/controllers/user/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -8,11 +8,11 @@ var db = require('../../db'); exports.engine = 'hbs'; -exports.before = function(req, res, next){ +exports.before = function (req, res, next) { var id = req.params.user_id; if (!id) return next(); // pretend to query a database... - process.nextTick(function(){ + process.nextTick(function () { req.user = db.users[id]; // cant find that user if (!req.user) return next('route'); @@ -21,19 +21,19 @@ exports.before = function(req, res, next){ }); }; -exports.list = function(req, res, next){ +exports.list = function (req, res, next) { res.render('list', { users: db.users }); }; -exports.edit = function(req, res, next){ +exports.edit = function (req, res, next) { res.render('edit', { user: req.user }); }; -exports.show = function(req, res, next){ +exports.show = function (req, res, next) { res.render('show', { user: req.user }); }; -exports.update = function(req, res, next){ +exports.update = function (req, res, next) { var body = req.body; req.user.name = body.user.name; res.message('Information updated!'); diff --git a/examples/mvc/db.js b/examples/mvc/db.js index 94d1480f9b7..8a779ba2d3c 100644 --- a/examples/mvc/db.js +++ b/examples/mvc/db.js @@ -1,16 +1,16 @@ -'use strict' +'use strict'; // faux database -var pets = exports.pets = []; +var pets = (exports.pets = []); pets.push({ name: 'Tobi', id: 0 }); pets.push({ name: 'Loki', id: 1 }); pets.push({ name: 'Jane', id: 2 }); pets.push({ name: 'Raul', id: 3 }); -var users = exports.users = []; +var users = (exports.users = []); -users.push({ name: 'TJ', pets: [pets[0], pets[1], pets[2]], id: 0 }); +users.push({ name: 'TJ', pets: [pets[0], pets[1], pets[2]], id: 0 }); users.push({ name: 'Guillermo', pets: [pets[3]], id: 1 }); users.push({ name: 'Nathan', pets: [], id: 2 }); diff --git a/examples/mvc/index.js b/examples/mvc/index.js index da4727b282d..c211aa99b81 100644 --- a/examples/mvc/index.js +++ b/examples/mvc/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -10,7 +10,7 @@ var path = require('path'); var session = require('express-session'); var methodOverride = require('method-override'); -var app = module.exports = express(); +var app = (module.exports = express()); // set our default template engine to "ejs" // which prevents the need for using file extensions @@ -21,7 +21,7 @@ app.set('views', path.join(__dirname, 'views')); // define a custom res.message() method // which stores messages in the session -app.response.message = function(msg){ +app.response.message = function (msg) { // reference `req.session` via the `this.req` reference var sess = this.req.session; // simply add the msg to an array for later @@ -37,27 +37,29 @@ if (!module.parent) app.use(logger('dev')); app.use(express.static(path.join(__dirname, 'public'))); // session support -app.use(session({ - resave: false, // don't save session if unmodified - saveUninitialized: false, // don't create session until something stored - secret: 'some secret here' -})); +app.use( + session({ + resave: false, // don't save session if unmodified + saveUninitialized: false, // don't create session until something stored + secret: 'some secret here', + }), +); // parse request bodies (req.body) -app.use(express.urlencoded({ extended: true })) +app.use(express.urlencoded({ extended: true })); // allow overriding methods in query (?_method=put) app.use(methodOverride('_method')); // expose the "messages" local variable when views are rendered -app.use(function(req, res, next){ +app.use(function (req, res, next) { var msgs = req.session.messages || []; // expose "messages" local variable res.locals.messages = msgs; // expose "hasMessages" - res.locals.hasMessages = !! msgs.length; + res.locals.hasMessages = !!msgs.length; /* This is equivalent: res.locals({ @@ -75,7 +77,7 @@ app.use(function(req, res, next){ // load controllers require('./lib/boot')(app, { verbose: !module.parent }); -app.use(function(err, req, res, next){ +app.use(function (err, req, res, next) { // log it if (!module.parent) console.error(err.stack); @@ -84,7 +86,7 @@ app.use(function(err, req, res, next){ }); // assume 404 since no middleware responded -app.use(function(req, res, next){ +app.use(function (req, res, next) { res.status(404).render('404', { url: req.originalUrl }); }); diff --git a/examples/mvc/lib/boot.js b/examples/mvc/lib/boot.js index 0216e5d76d6..d2b0f338080 100644 --- a/examples/mvc/lib/boot.js +++ b/examples/mvc/lib/boot.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -8,11 +8,11 @@ var express = require('../../..'); var fs = require('fs'); var path = require('path'); -module.exports = function(parent, options){ +module.exports = function (parent, options) { var dir = path.join(__dirname, '..', 'controllers'); var verbose = options.verbose; - fs.readdirSync(dir).forEach(function(name){ - var file = path.join(dir, name) + fs.readdirSync(dir).forEach(function (name) { + var file = path.join(dir, name); if (!fs.statSync(file).isDirectory()) return; verbose && console.log('\n %s:', name); var obj = require(file); @@ -70,10 +70,17 @@ module.exports = function(parent, options){ // before middleware support if (obj.before) { app[method](url, obj.before, handler); - verbose && console.log(' %s %s -> before -> %s', method.toUpperCase(), url, key); + verbose && + console.log( + ' %s %s -> before -> %s', + method.toUpperCase(), + url, + key, + ); } else { app[method](url, handler); - verbose && console.log(' %s %s -> %s', method.toUpperCase(), url, key); + verbose && + console.log(' %s %s -> %s', method.toUpperCase(), url, key); } } diff --git a/examples/online/index.js b/examples/online/index.js index 0b5fdffc86a..07668c48384 100644 --- a/examples/online/index.js +++ b/examples/online/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; // install redis first: // https://redis.io/ @@ -27,7 +27,7 @@ var app = express(); // activity tracking, in this case using // the UA string, you would use req.user.id etc -app.use(function(req, res, next){ +app.use(function (req, res, next) { // fire-and-forget online.add(req.headers['user-agent']); next(); @@ -38,17 +38,23 @@ app.use(function(req, res, next){ */ function list(ids) { - return ''; + return ( + '' + ); } /** * GET users online. */ -app.get('/', function(req, res, next){ - online.last(5, function(err, ids){ +app.get('/', function (req, res, next) { + online.last(5, function (err, ids) { if (err) return next(err); res.send('

Users online: ' + ids.length + '

' + list(ids)); }); diff --git a/examples/params/index.js b/examples/params/index.js index f3cd8457eb5..b1818afc27d 100644 --- a/examples/params/index.js +++ b/examples/params/index.js @@ -1,29 +1,29 @@ -'use strict' +'use strict'; /** * Module dependencies. */ -var createError = require('http-errors') +var createError = require('http-errors'); var express = require('../../'); -var app = module.exports = express(); +var app = (module.exports = express()); // Faux database var users = [ - { name: 'tj' } - , { name: 'tobi' } - , { name: 'loki' } - , { name: 'jane' } - , { name: 'bandit' } + { name: 'tj' }, + { name: 'tobi' }, + { name: 'loki' }, + { name: 'jane' }, + { name: 'bandit' }, ]; // Convert :to and :from to integers -app.param(['to', 'from'], function(req, res, next, num, name){ +app.param(['to', 'from'], function (req, res, next, num, name) { req.params[name] = parseInt(num, 10); - if( isNaN(req.params[name]) ){ - next(createError(400, 'failed to parseInt '+num)); + if (isNaN(req.params[name])) { + next(createError(400, 'failed to parseInt ' + num)); } else { next(); } @@ -31,8 +31,8 @@ app.param(['to', 'from'], function(req, res, next, num, name){ // Load user by id -app.param('user', function(req, res, next, id){ - if (req.user = users[id]) { +app.param('user', function (req, res, next, id) { + if ((req.user = users[id])) { next(); } else { next(createError(404, 'failed to find user')); @@ -43,7 +43,7 @@ app.param('user', function(req, res, next, id){ * GET index. */ -app.get('/', function(req, res){ +app.get('/', function (req, res) { res.send('Visit /user/0 or /users/0-2'); }); @@ -62,7 +62,9 @@ app.get('/user/:user', function (req, res) { app.get('/users/:from-:to', function (req, res) { var from = req.params.from; var to = req.params.to; - var names = users.map(function(user){ return user.name; }); + var names = users.map(function (user) { + return user.name; + }); res.send('users ' + names.slice(from, to + 1).join(', ')); }); diff --git a/examples/resource/index.js b/examples/resource/index.js index 627ab24c5a2..7188039a621 100644 --- a/examples/resource/index.js +++ b/examples/resource/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -6,20 +6,20 @@ var express = require('../../'); -var app = module.exports = express(); +var app = (module.exports = express()); // Ad-hoc example resource method -app.resource = function(path, obj) { +app.resource = function (path, obj) { this.get(path, obj.index); - this.get(path + '/:a..:b{.:format}', function(req, res){ + this.get(path + '/:a..:b{.:format}', function (req, res) { var a = parseInt(req.params.a, 10); var b = parseInt(req.params.b, 10); var format = req.params.format; obj.range(req, res, a, b, format); }); this.get(path + '/:id', obj.show); - this.delete(path + '/:id', function(req, res){ + this.delete(path + '/:id', function (req, res) { var id = parseInt(req.params.id, 10); obj.destroy(req, res, id); }); @@ -28,29 +28,29 @@ app.resource = function(path, obj) { // Fake records var users = [ - { name: 'tj' } - , { name: 'ciaran' } - , { name: 'aaron' } - , { name: 'guillermo' } - , { name: 'simon' } - , { name: 'tobi' } + { name: 'tj' }, + { name: 'ciaran' }, + { name: 'aaron' }, + { name: 'guillermo' }, + { name: 'simon' }, + { name: 'tobi' }, ]; // Fake controller. var User = { - index: function(req, res){ + index: function (req, res) { res.send(users); }, - show: function(req, res){ + show: function (req, res) { res.send(users[req.params.id] || { error: 'Cannot find user' }); }, - destroy: function(req, res, id){ + destroy: function (req, res, id) { var destroyed = id in users; delete users[id]; res.send(destroyed ? 'destroyed' : 'Cannot find user'); }, - range: function(req, res, a, b, format){ + range: function (req, res, a, b, format) { var range = users.slice(a, b + 1); switch (format) { case 'json': @@ -58,13 +58,18 @@ var User = { break; case 'html': default: - var html = ''; + var html = + ''; res.send(html); break; } - } + }, }; // curl http://localhost:3000/users -- responds with all users @@ -75,17 +80,19 @@ var User = { app.resource('/users', User); -app.get('/', function(req, res){ - res.send([ - '

Examples:

' - ].join('\n')); +app.get('/', function (req, res) { + res.send( + [ + '

Examples:

', + ].join('\n'), + ); }); /* istanbul ignore next */ diff --git a/examples/route-map/index.js b/examples/route-map/index.js index 2bc28bd4b26..3baacc7ac80 100644 --- a/examples/route-map/index.js +++ b/examples/route-map/index.js @@ -1,17 +1,17 @@ -'use strict' +'use strict'; /** * Module dependencies. */ -var escapeHtml = require('escape-html') +var escapeHtml = require('escape-html'); var express = require('../../lib/express'); -var verbose = process.env.NODE_ENV !== 'test' +var verbose = process.env.NODE_ENV !== 'test'; -var app = module.exports = express(); +var app = (module.exports = express()); -app.map = function(a, route){ +app.map = function (a, route) { route = route || ''; for (var key in a) { switch (typeof a[key]) { @@ -29,27 +29,32 @@ app.map = function(a, route){ }; var users = { - list: function(req, res){ + list: function (req, res) { res.send('user list'); }, - get: function(req, res){ - res.send('user ' + escapeHtml(req.params.uid)) + get: function (req, res) { + res.send('user ' + escapeHtml(req.params.uid)); }, - delete: function(req, res){ + delete: function (req, res) { res.send('delete users'); - } + }, }; var pets = { - list: function(req, res){ - res.send('user ' + escapeHtml(req.params.uid) + '\'s pets') + list: function (req, res) { + res.send('user ' + escapeHtml(req.params.uid) + "'s pets"); }, - delete: function(req, res){ - res.send('delete ' + escapeHtml(req.params.uid) + '\'s pet ' + escapeHtml(req.params.pid)) - } + delete: function (req, res) { + res.send( + 'delete ' + + escapeHtml(req.params.uid) + + "'s pet " + + escapeHtml(req.params.pid), + ); + }, }; app.map({ @@ -61,11 +66,11 @@ app.map({ '/pets': { get: pets.list, '/:pid': { - delete: pets.delete - } - } - } - } + delete: pets.delete, + }, + }, + }, + }, }); /* istanbul ignore next */ diff --git a/examples/route-middleware/index.js b/examples/route-middleware/index.js index 44ec13a95b8..809f52d6120 100644 --- a/examples/route-middleware/index.js +++ b/examples/route-middleware/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -17,9 +17,14 @@ var app = express(); // Dummy users var users = [ - { id: 0, name: 'tj', email: 'tj@vision-media.ca', role: 'member' } - , { id: 1, name: 'ciaran', email: 'ciaranj@gmail.com', role: 'member' } - , { id: 2, name: 'aaron', email: 'aaron.heckmann+github@gmail.com', role: 'admin' } + { id: 0, name: 'tj', email: 'tj@vision-media.ca', role: 'member' }, + { id: 1, name: 'ciaran', email: 'ciaranj@gmail.com', role: 'member' }, + { + id: 2, + name: 'aaron', + email: 'aaron.heckmann+github@gmail.com', + role: 'admin', + }, ]; function loadUser(req, res, next) { @@ -48,13 +53,13 @@ function andRestrictToSelf(req, res, next) { } function andRestrictTo(role) { - return function(req, res, next) { + return function (req, res, next) { if (req.authenticatedUser.role === role) { next(); } else { next(new Error('Unauthorized')); } - } + }; } // Middleware for faux authentication @@ -62,24 +67,24 @@ function andRestrictTo(role) { // but this illustrates how an authenticated user // may interact with middleware -app.use(function(req, res, next){ +app.use(function (req, res, next) { req.authenticatedUser = users[0]; next(); }); -app.get('/', function(req, res){ +app.get('/', function (req, res) { res.redirect('/user/0'); }); -app.get('/user/:id', loadUser, function(req, res){ +app.get('/user/:id', loadUser, function (req, res) { res.send('Viewing user ' + req.user.name); }); -app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){ +app.get('/user/:id/edit', loadUser, andRestrictToSelf, function (req, res) { res.send('Editing user ' + req.user.name); }); -app.delete('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){ +app.delete('/user/:id', loadUser, andRestrictTo('admin'), function (req, res) { res.send('Deleted user ' + req.user.name); }); diff --git a/examples/route-separation/index.js b/examples/route-separation/index.js index a471a4b0912..786dad12927 100644 --- a/examples/route-separation/index.js +++ b/examples/route-separation/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -28,7 +28,7 @@ if (!module.parent) { app.use(methodOverride('_method')); app.use(cookieParser()); -app.use(express.urlencoded({ extended: true })) +app.use(express.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, 'public'))); // General diff --git a/examples/route-separation/post.js b/examples/route-separation/post.js index 3a8e3a2d225..0a2b671be29 100644 --- a/examples/route-separation/post.js +++ b/examples/route-separation/post.js @@ -1,13 +1,13 @@ -'use strict' +'use strict'; // Fake posts database var posts = [ { title: 'Foo', body: 'some foo bar' }, { title: 'Foo bar', body: 'more foo bar' }, - { title: 'Foo bar baz', body: 'more foo bar baz' } + { title: 'Foo bar baz', body: 'more foo bar baz' }, ]; -exports.list = function(req, res){ +exports.list = function (req, res) { res.render('posts', { title: 'Posts', posts: posts }); }; diff --git a/examples/route-separation/site.js b/examples/route-separation/site.js index aee36d1bd72..f4496959cea 100644 --- a/examples/route-separation/site.js +++ b/examples/route-separation/site.js @@ -1,5 +1,5 @@ -'use strict' +'use strict'; -exports.index = function(req, res){ +exports.index = function (req, res) { res.render('index', { title: 'Route Separation Example' }); }; diff --git a/examples/route-separation/user.js b/examples/route-separation/user.js index bc6fbd7baf3..75c03b3c3c6 100644 --- a/examples/route-separation/user.js +++ b/examples/route-separation/user.js @@ -1,17 +1,17 @@ -'use strict' +'use strict'; // Fake user database var users = [ { name: 'TJ', email: 'tj@vision-media.ca' }, - { name: 'Tobi', email: 'tobi@vision-media.ca' } + { name: 'Tobi', email: 'tobi@vision-media.ca' }, ]; -exports.list = function(req, res){ +exports.list = function (req, res) { res.render('users', { title: 'Users', users: users }); }; -exports.load = function(req, res, next){ +exports.load = function (req, res, next) { var id = req.params.id; req.user = users[id]; if (req.user) { @@ -23,21 +23,21 @@ exports.load = function(req, res, next){ } }; -exports.view = function(req, res){ +exports.view = function (req, res) { res.render('users/view', { title: 'Viewing user ' + req.user.name, - user: req.user + user: req.user, }); }; -exports.edit = function(req, res){ +exports.edit = function (req, res) { res.render('users/edit', { title: 'Editing user ' + req.user.name, - user: req.user + user: req.user, }); }; -exports.update = function(req, res){ +exports.update = function (req, res) { // Normally you would handle all kinds of // validation and save back to the db var user = req.body.user; diff --git a/examples/search/index.js b/examples/search/index.js index 4b57168987f..50a6ca3c6e9 100644 --- a/examples/search/index.js +++ b/examples/search/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; // install redis first: // https://redis.io/ @@ -35,9 +35,9 @@ db.sadd('cat', 'luna'); * GET search for :query. */ -app.get('/search/:query?', function(req, res, next){ +app.get('/search/:query?', function (req, res, next) { var query = req.params.query; - db.smembers(query, function(err, vals){ + db.smembers(query, function (err, vals) { if (err) return next(err); res.send(vals); }); @@ -50,7 +50,7 @@ app.get('/search/:query?', function(req, res, next){ * template. */ -app.get('/client.js', function(req, res){ +app.get('/client.js', function (req, res) { res.sendFile(path.join(__dirname, 'client.js')); }); diff --git a/examples/search/public/client.js b/examples/search/public/client.js index cd43faf71e0..9e92baa82a8 100644 --- a/examples/search/public/client.js +++ b/examples/search/public/client.js @@ -1,15 +1,19 @@ -'use strict' +'use strict'; var search = document.querySelector('[type=search]'); var code = document.querySelector('pre'); -search.addEventListener('keyup', function(){ - var xhr = new XMLHttpRequest; - xhr.open('GET', '/search/' + search.value, true); - xhr.onreadystatechange = function(){ - if (xhr.readyState === 4) { - code.textContent = xhr.responseText; - } - }; - xhr.send(); -}, false); +search.addEventListener( + 'keyup', + function () { + var xhr = new XMLHttpRequest(); + xhr.open('GET', '/search/' + search.value, true); + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + code.textContent = xhr.responseText; + } + }; + xhr.send(); + }, + false, +); diff --git a/examples/session/index.js b/examples/session/index.js index 2bb2b109c82..feb5ed6c05e 100644 --- a/examples/session/index.js +++ b/examples/session/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; // install redis first: // https://redis.io/ @@ -13,13 +13,15 @@ var session = require('express-session'); var app = express(); // Populates req.session -app.use(session({ - resave: false, // don't save session if unmodified - saveUninitialized: false, // don't create session until something stored - secret: 'keyboard cat' -})); +app.use( + session({ + resave: false, // don't save session if unmodified + saveUninitialized: false, // don't create session until something stored + secret: 'keyboard cat', + }), +); -app.get('/', function(req, res){ +app.get('/', function (req, res) { var body = ''; if (req.session.views) { ++req.session.views; @@ -27,7 +29,9 @@ app.get('/', function(req, res){ req.session.views = 1; body += '

First time visiting? view this page in several browsers :)

'; } - res.send(body + '

viewed ' + req.session.views + ' times.

'); + res.send( + body + '

viewed ' + req.session.views + ' times.

', + ); }); /* istanbul ignore next */ diff --git a/examples/session/redis.js b/examples/session/redis.js index bbbdc7fd3e5..666e66a1fce 100644 --- a/examples/session/redis.js +++ b/examples/session/redis.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -17,14 +17,16 @@ var app = express(); app.use(logger('dev')); // Populates req.session -app.use(session({ - resave: false, // don't save session if unmodified - saveUninitialized: false, // don't create session until something stored - secret: 'keyboard cat', - store: new RedisStore -})); - -app.get('/', function(req, res){ +app.use( + session({ + resave: false, // don't save session if unmodified + saveUninitialized: false, // don't create session until something stored + secret: 'keyboard cat', + store: new RedisStore(), + }), +); + +app.get('/', function (req, res) { var body = ''; if (req.session.views) { ++req.session.views; @@ -32,7 +34,9 @@ app.get('/', function(req, res){ req.session.views = 1; body += '

First time visiting? view this page in several browsers :)

'; } - res.send(body + '

viewed ' + req.session.views + ' times.

'); + res.send( + body + '

viewed ' + req.session.views + ' times.

', + ); }); app.listen(3000); diff --git a/examples/static-files/index.js b/examples/static-files/index.js index 609c546b470..b942de9b5cd 100644 --- a/examples/static-files/index.js +++ b/examples/static-files/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. diff --git a/examples/vhost/index.js b/examples/vhost/index.js index a9499356b42..1bd9f199ec5 100644 --- a/examples/vhost/index.js +++ b/examples/vhost/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -22,11 +22,11 @@ var main = express(); if (!module.parent) main.use(logger('dev')); -main.get('/', function(req, res){ +main.get('/', function (req, res) { res.send('Hello from main app!'); }); -main.get('/:sub', function(req, res){ +main.get('/:sub', function (req, res) { res.send('requested ' + req.params.sub); }); @@ -34,14 +34,14 @@ main.get('/:sub', function(req, res){ var redirect = express(); -redirect.use(function(req, res){ +redirect.use(function (req, res) { if (!module.parent) console.log(req.vhost); res.redirect('http://example.com:3000/' + req.vhost[0]); }); // Vhost app -var app = module.exports = express(); +var app = (module.exports = express()); app.use(vhost('*.example.com', redirect)); // Serves all subdomains via Redirect app app.use(vhost('example.com', main)); // Serves top level domain via Main server app diff --git a/examples/view-constructor/github-view.js b/examples/view-constructor/github-view.js index 43d29336cac..5b89a83f14b 100644 --- a/examples/view-constructor/github-view.js +++ b/examples/view-constructor/github-view.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -20,7 +20,7 @@ module.exports = GithubView; * render templates from a database etc. */ -function GithubView(name, options){ +function GithubView(name, options) { this.name = name; options = options || {}; this.engine = options.engines[extname(name)]; @@ -33,21 +33,25 @@ function GithubView(name, options){ * Render the view. */ -GithubView.prototype.render = function(options, fn){ +GithubView.prototype.render = function (options, fn) { var self = this; var opts = { host: 'raw.githubusercontent.com', port: 443, path: this.path, - method: 'GET' + method: 'GET', }; - https.request(opts, function(res) { - var buf = ''; - res.setEncoding('utf8'); - res.on('data', function(str){ buf += str }); - res.on('end', function(){ - self.engine(buf, options, fn); - }); - }).end(); + https + .request(opts, function (res) { + var buf = ''; + res.setEncoding('utf8'); + res.on('data', function (str) { + buf += str; + }); + res.on('end', function () { + self.engine(buf, options, fn); + }); + }) + .end(); }; diff --git a/examples/view-constructor/index.js b/examples/view-constructor/index.js index 3d673670e31..357598dd90b 100644 --- a/examples/view-constructor/index.js +++ b/examples/view-constructor/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -8,17 +8,17 @@ var express = require('../../'); var GithubView = require('./github-view'); var md = require('marked').parse; -var app = module.exports = express(); +var app = (module.exports = express()); // register .md as an engine in express view system -app.engine('md', function(str, options, fn){ +app.engine('md', function (str, options, fn) { try { var html = md(str); - html = html.replace(/\{([^}]+)\}/g, function(_, name){ + html = html.replace(/\{([^}]+)\}/g, function (_, name) { return options[name] || ''; }); fn(null, html); - } catch(err) { + } catch (err) { fn(err); } }); @@ -29,14 +29,14 @@ app.set('views', 'expressjs/express'); // register a new view constructor app.set('view', GithubView); -app.get('/', function(req, res){ +app.get('/', function (req, res) { // rendering a view relative to the repo. // app.locals, res.locals, and locals passed // work like they normally would res.render('examples/markdown/views/index.md', { title: 'Example' }); }); -app.get('/Readme.md', function(req, res){ +app.get('/Readme.md', function (req, res) { // rendering a view from https://github.com/expressjs/express/blob/master/Readme.md res.render('Readme.md'); }); diff --git a/examples/view-locals/index.js b/examples/view-locals/index.js index a2af24f3553..14570f390f0 100644 --- a/examples/view-locals/index.js +++ b/examples/view-locals/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -15,7 +15,7 @@ app.set('view engine', 'ejs'); // filter ferrets only function ferrets(user) { - return user.species === 'ferret' + return user.species === 'ferret'; } // naive nesting approach, @@ -23,55 +23,49 @@ function ferrets(user) { // in order to expose the "count" // and "users" locals -app.get('/', function(req, res, next){ - User.count(function(err, count){ +app.get('/', function (req, res, next) { + User.count(function (err, count) { if (err) return next(err); - User.all(function(err, users){ + User.all(function (err, users) { if (err) return next(err); res.render('index', { title: 'Users', count: count, - users: users.filter(ferrets) + users: users.filter(ferrets), }); - }) - }) + }); + }); }); - - - // this approach is cleaner, // less nesting and we have // the variables available // on the request object function count(req, res, next) { - User.count(function(err, count){ + User.count(function (err, count) { if (err) return next(err); req.count = count; next(); - }) + }); } function users(req, res, next) { - User.all(function(err, users){ + User.all(function (err, users) { if (err) return next(err); req.users = users; next(); - }) + }); } app.get('/middleware', count, users, function (req, res) { res.render('index', { title: 'Users', count: req.count, - users: req.users.filter(ferrets) + users: req.users.filter(ferrets), }); }); - - - // this approach is much like the last // however we're explicitly exposing // the locals within each middleware @@ -84,19 +78,19 @@ app.get('/middleware', count, users, function (req, res) { // is more flexible with `req.users`. function count2(req, res, next) { - User.count(function(err, count){ + User.count(function (err, count) { if (err) return next(err); res.locals.count = count; next(); - }) + }); } function users2(req, res, next) { - User.all(function(err, users){ + User.all(function (err, users) { if (err) return next(err); res.locals.users = users.filter(ferrets); next(); - }) + }); } app.get('/middleware-locals', count2, users2, function (req, res) { diff --git a/examples/view-locals/user.js b/examples/view-locals/user.js index aaa6f85ff0e..f228e52e849 100644 --- a/examples/view-locals/user.js +++ b/examples/view-locals/user.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = User; @@ -10,17 +10,17 @@ function User(name, age, species) { this.species = species; } -User.all = function(fn){ +User.all = function (fn) { // process.nextTick makes sure this function API // behaves in an asynchronous manner, like if it // was a real DB query to read all users. - process.nextTick(function(){ + process.nextTick(function () { fn(null, users); }); }; -User.count = function(fn){ - process.nextTick(function(){ +User.count = function (fn) { + process.nextTick(function () { fn(null, users.length); }); }; diff --git a/examples/web-service/index.js b/examples/web-service/index.js index d1a90362153..d6327d179bf 100644 --- a/examples/web-service/index.js +++ b/examples/web-service/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; /** * Module dependencies. @@ -6,7 +6,7 @@ var express = require('../../'); -var app = module.exports = express(); +var app = (module.exports = express()); // create an error with .status. we // can then use the property in our @@ -27,14 +27,14 @@ function error(status, msg) { // meaning only paths prefixed with "/api" // will cause this middleware to be invoked -app.use('/api', function(req, res, next){ +app.use('/api', function (req, res, next) { var key = req.query['api-key']; // key isn't present if (!key) return next(error(400, 'api key required')); // key is invalid - if (apiKeys.indexOf(key) === -1) return next(error(401, 'invalid api key')) + if (apiKeys.indexOf(key) === -1) return next(error(401, 'invalid api key')); // all good, store req.key for route access req.key = key; @@ -53,19 +53,15 @@ var apiKeys = ['foo', 'bar', 'baz']; var repos = [ { name: 'express', url: 'https://github.com/expressjs/express' }, { name: 'stylus', url: 'https://github.com/learnboost/stylus' }, - { name: 'cluster', url: 'https://github.com/learnboost/cluster' } + { name: 'cluster', url: 'https://github.com/learnboost/cluster' }, ]; -var users = [ - { name: 'tobi' } - , { name: 'loki' } - , { name: 'jane' } -]; +var users = [{ name: 'tobi' }, { name: 'loki' }, { name: 'jane' }]; var userRepos = { - tobi: [repos[0], repos[1]] - , loki: [repos[1]] - , jane: [repos[2]] + tobi: [repos[0], repos[1]], + loki: [repos[1]], + jane: [repos[2]], }; // we now can assume the api key is valid, @@ -82,7 +78,7 @@ app.get('/api/repos', function (req, res) { }); // example: http://localhost:3000/api/user/tobi/repos/?api-key=foo -app.get('/api/user/:name/repos', function(req, res, next){ +app.get('/api/user/:name/repos', function (req, res, next) { var name = req.params.name; var user = userRepos[name]; @@ -95,7 +91,7 @@ app.get('/api/user/:name/repos', function(req, res, next){ // it will be passed through the defined middleware // in order, but ONLY those with an arity of 4, ignoring // regular middleware. -app.use(function(err, req, res, next){ +app.use(function (err, req, res, next) { // whatever you want here, feel free to populate // properties on `err` to treat it differently in here. res.status(err.status || 500); @@ -105,9 +101,9 @@ app.use(function(err, req, res, next){ // our custom JSON 404 middleware. Since it's placed last // it will be the last middleware called, if all others // invoke next() and do not respond. -app.use(function(req, res){ +app.use(function (req, res) { res.status(404); - res.send({ error: "Sorry, can't find that" }) + res.send({ error: "Sorry, can't find that" }); }); /* istanbul ignore next */ diff --git a/lib/application.js b/lib/application.js index b19055ec829..b6a67e467eb 100644 --- a/lib/application.js +++ b/lib/application.js @@ -23,7 +23,7 @@ var compileQueryParser = require('./utils').compileQueryParser; var compileTrust = require('./utils').compileTrust; var merge = require('utils-merge'); var resolve = require('path').resolve; -var once = require('once') +var once = require('once'); var Router = require('router'); /** @@ -38,7 +38,7 @@ var flatten = Array.prototype.flat; * Application prototype. */ -var app = exports = module.exports = {}; +var app = (exports = module.exports = {}); /** * Variable for trust proxy inheritance back-compat @@ -74,12 +74,12 @@ app.init = function init() { if (router === null) { router = new Router({ caseSensitive: this.enabled('case sensitive routing'), - strict: this.enabled('strict routing') + strict: this.enabled('strict routing'), }); } return router; - } + }, }); }; @@ -95,31 +95,33 @@ app.defaultConfiguration = function defaultConfiguration() { this.enable('x-powered-by'); this.set('etag', 'weak'); this.set('env', env); - this.set('query parser', 'simple') + this.set('query parser', 'simple'); this.set('subdomain offset', 2); this.set('trust proxy', false); // trust proxy inherit back-compat Object.defineProperty(this.settings, trustProxyDefaultSymbol, { configurable: true, - value: true + value: true, }); debug('booting in %s mode', env); this.on('mount', function onmount(parent) { // inherit trust proxy - if (this.settings[trustProxyDefaultSymbol] === true - && typeof parent.settings['trust proxy fn'] === 'function') { + if ( + this.settings[trustProxyDefaultSymbol] === true && + typeof parent.settings['trust proxy fn'] === 'function' + ) { delete this.settings['trust proxy']; delete this.settings['trust proxy fn']; } // inherit protos - Object.setPrototypeOf(this.request, parent.request) - Object.setPrototypeOf(this.response, parent.response) - Object.setPrototypeOf(this.engines, parent.engines) - Object.setPrototypeOf(this.settings, parent.settings) + Object.setPrototypeOf(this.request, parent.request); + Object.setPrototypeOf(this.response, parent.response); + Object.setPrototypeOf(this.engines, parent.engines); + Object.setPrototypeOf(this.settings, parent.settings); }); // setup locals @@ -152,10 +154,12 @@ app.defaultConfiguration = function defaultConfiguration() { app.handle = function handle(req, res, callback) { // final handler - var done = callback || finalhandler(req, res, { - env: this.get('env'), - onerror: logerror.bind(this) - }); + var done = + callback || + finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this), + }); // set powered by header if (this.enabled('x-powered-by')) { @@ -167,8 +171,8 @@ app.handle = function handle(req, res, callback) { res.req = req; // alter the prototypes - Object.setPrototypeOf(req, this.request) - Object.setPrototypeOf(res, this.response) + Object.setPrototypeOf(req, this.request); + Object.setPrototypeOf(res, this.response); // setup locals if (!res.locals) { @@ -211,7 +215,7 @@ app.use = function use(fn) { var fns = flatten.call(slice.call(arguments, offset), Infinity); if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') + throw new TypeError('app.use() requires a middleware function'); } // get router @@ -231,8 +235,8 @@ app.use = function use(fn) { router.use(path, function mounted_app(req, res, next) { var orig = req.app; fn.handle(req, res, function (err) { - Object.setPrototypeOf(req, orig.request) - Object.setPrototypeOf(res, orig.response) + Object.setPrototypeOf(req, orig.request); + Object.setPrototypeOf(res, orig.response); next(err); }); }); @@ -298,9 +302,7 @@ app.engine = function engine(ext, fn) { } // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; + var extension = ext[0] !== '.' ? '.' + ext : ext; // store engine this.engines[extension] = fn; @@ -374,7 +376,7 @@ app.set = function set(setting, val) { // trust proxy inherit back-compat Object.defineProperty(this.settings, trustProxyDefaultSymbol, { configurable: true, - value: false + value: false, }); break; @@ -398,9 +400,7 @@ app.set = function set(setting, val) { */ app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; + return this.parent ? this.parent.path() + this.mountpath : ''; }; /** @@ -469,8 +469,8 @@ app.disable = function disable(setting) { * Delegate `.VERB(...)` calls to `router.VERB(...)`. */ -methods.forEach(function(method){ - app[method] = function(path){ +methods.forEach(function (method) { + app[method] = function (path) { if (method === 'get' && arguments.length === 1) { // app.get(setting) return this.set(path); @@ -562,14 +562,21 @@ app.render = function render(name, options, callback) { view = new View(name, { defaultEngine: this.get('view engine'), root: this.get('views'), - engines: engines + engines: engines, }); if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 - ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' - : 'directory "' + view.root + '"' - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + var dirs = + Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + + view.root.slice(0, -1).join('", "') + + '" or "' + + view.root[view.root.length - 1] + + '"' + : 'directory "' + view.root + '"'; + var err = new Error( + 'Failed to lookup view "' + name + '" in views ' + dirs, + ); err.view = view; return done(err); } @@ -605,15 +612,15 @@ app.render = function render(name, options, callback) { * @public */ -app.listen = function listen () { - var server = http.createServer(this) - var args = Array.prototype.slice.call(arguments) +app.listen = function listen() { + var server = http.createServer(this); + var args = Array.prototype.slice.call(arguments); if (typeof args[args.length - 1] === 'function') { - var done = args[args.length - 1] = once(args[args.length - 1]) - server.once('error', done) + var done = (args[args.length - 1] = once(args[args.length - 1])); + server.once('error', done); } - return server.listen.apply(server, args) -} + return server.listen.apply(server, args); +}; /** * Log error using console.error. diff --git a/lib/express.js b/lib/express.js index b4ef2996360..00d2c62ec2e 100644 --- a/lib/express.js +++ b/lib/express.js @@ -12,7 +12,7 @@ * Module dependencies. */ -var bodyParser = require('body-parser') +var bodyParser = require('body-parser'); var EventEmitter = require('events').EventEmitter; var mixin = require('merge-descriptors'); var proto = require('./application'); @@ -34,7 +34,7 @@ exports = module.exports = createApplication; */ function createApplication() { - var app = function(req, res, next) { + var app = function (req, res, next) { app.handle(req, res, next); }; @@ -43,13 +43,13 @@ function createApplication() { // expose the prototype that will get set on requests app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) + app: { configurable: true, enumerable: true, writable: true, value: app }, + }); // expose the prototype that will get set on responses app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) + app: { configurable: true, enumerable: true, writable: true, value: app }, + }); app.init(); return app; @@ -74,8 +74,8 @@ exports.Router = Router; * Expose middleware */ -exports.json = bodyParser.json -exports.raw = bodyParser.raw +exports.json = bodyParser.json; +exports.raw = bodyParser.raw; exports.static = require('serve-static'); -exports.text = bodyParser.text -exports.urlencoded = bodyParser.urlencoded +exports.text = bodyParser.text; +exports.urlencoded = bodyParser.urlencoded; diff --git a/lib/request.js b/lib/request.js index 372a9915e96..f90b01b9e24 100644 --- a/lib/request.js +++ b/lib/request.js @@ -27,14 +27,14 @@ var proxyaddr = require('proxy-addr'); * @public */ -var req = Object.create(http.IncomingMessage.prototype) +var req = Object.create(http.IncomingMessage.prototype); /** * Module exports. * @public */ -module.exports = req +module.exports = req; /** * Return request header. @@ -60,8 +60,7 @@ module.exports = req * @public */ -req.get = -req.header = function header(name) { +req.get = req.header = function header(name) { if (!name) { throw new TypeError('name argument is required to req.get'); } @@ -75,8 +74,7 @@ req.header = function header(name) { switch (lc) { case 'referer': case 'referrer': - return this.headers.referrer - || this.headers.referer; + return this.headers.referrer || this.headers.referer; default: return this.headers[lc]; } @@ -128,7 +126,7 @@ req.header = function header(name) { * @public */ -req.accepts = function(){ +req.accepts = function () { var accept = accepts(this); return accept.types.apply(accept, arguments); }; @@ -141,7 +139,7 @@ req.accepts = function(){ * @public */ -req.acceptsEncodings = function(){ +req.acceptsEncodings = function () { var accept = accepts(this); return accept.encodings.apply(accept, arguments); }; @@ -155,7 +153,7 @@ req.acceptsEncodings = function(){ * @public */ -req.acceptsCharsets = function(){ +req.acceptsCharsets = function () { var accept = accepts(this); return accept.charsets.apply(accept, arguments); }; @@ -169,7 +167,7 @@ req.acceptsCharsets = function(){ * @public */ -req.acceptsLanguages = function(){ +req.acceptsLanguages = function () { var accept = accepts(this); return accept.languages.apply(accept, arguments); }; @@ -215,7 +213,7 @@ req.range = function range(size, options) { * @api public */ -defineGetter(req, 'query', function query(){ +defineGetter(req, 'query', function query() { var queryparse = this.app.get('query parser fn'); if (!queryparse) { @@ -282,10 +280,8 @@ req.is = function is(types) { * @public */ -defineGetter(req, 'protocol', function protocol(){ - var proto = this.connection.encrypted - ? 'https' - : 'http'; +defineGetter(req, 'protocol', function protocol() { + var proto = this.connection.encrypted ? 'https' : 'http'; var trust = this.app.get('trust proxy fn'); if (!trust(this.connection.remoteAddress, 0)) { @@ -294,12 +290,10 @@ defineGetter(req, 'protocol', function protocol(){ // Note: X-Forwarded-Proto is normally only ever a // single value, but this is to be safe. - var header = this.get('X-Forwarded-Proto') || proto - var index = header.indexOf(',') + var header = this.get('X-Forwarded-Proto') || proto; + var index = header.indexOf(','); - return index !== -1 - ? header.substring(0, index).trim() - : header.trim() + return index !== -1 ? header.substring(0, index).trim() : header.trim(); }); /** @@ -311,7 +305,7 @@ defineGetter(req, 'protocol', function protocol(){ * @public */ -defineGetter(req, 'secure', function secure(){ +defineGetter(req, 'secure', function secure() { return this.protocol === 'https'; }); @@ -325,7 +319,7 @@ defineGetter(req, 'secure', function secure(){ * @public */ -defineGetter(req, 'ip', function ip(){ +defineGetter(req, 'ip', function ip() { var trust = this.app.get('trust proxy fn'); return proxyaddr(this, trust); }); @@ -348,9 +342,9 @@ defineGetter(req, 'ips', function ips() { // reverse the order (to farthest -> closest) // and remove socket address - addrs.reverse().pop() + addrs.reverse().pop(); - return addrs + return addrs; }); /** @@ -374,9 +368,7 @@ defineGetter(req, 'subdomains', function subdomains() { if (!hostname) return []; var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) - ? hostname.split('.').reverse() - : [hostname]; + var subdomains = !isIP(hostname) ? hostname.split('.').reverse() : [hostname]; return subdomains.slice(offset); }); @@ -403,7 +395,7 @@ defineGetter(req, 'path', function path() { * @public */ -defineGetter(req, 'host', function host(){ +defineGetter(req, 'host', function host() { var trust = this.app.get('trust proxy fn'); var val = this.get('X-Forwarded-Host'); @@ -412,7 +404,7 @@ defineGetter(req, 'host', function host(){ } else if (val.indexOf(',') !== -1) { // Note: X-Forwarded-Host is normally only ever a // single value, but this is to be safe. - val = val.substring(0, val.indexOf(',')).trimRight() + val = val.substring(0, val.indexOf(',')).trimRight(); } return val || undefined; @@ -429,20 +421,16 @@ defineGetter(req, 'host', function host(){ * @api public */ -defineGetter(req, 'hostname', function hostname(){ +defineGetter(req, 'hostname', function hostname() { var host = this.host; if (!host) return; // IPv6 literal support - var offset = host[0] === '[' - ? host.indexOf(']') + 1 - : 0; + var offset = host[0] === '[' ? host.indexOf(']') + 1 : 0; var index = host.indexOf(':', offset); - return index !== -1 - ? host.substring(0, index) - : host; + return index !== -1 ? host.substring(0, index) : host; }); /** @@ -454,10 +442,10 @@ defineGetter(req, 'hostname', function hostname(){ * @public */ -defineGetter(req, 'fresh', function(){ +defineGetter(req, 'fresh', function () { var method = this.method; - var res = this.res - var status = res.statusCode + var res = this.res; + var status = res.statusCode; // GET or HEAD for weak freshness validation only if ('GET' !== method && 'HEAD' !== method) return false; @@ -465,9 +453,9 @@ defineGetter(req, 'fresh', function(){ // 2xx or 304 as per rfc2616 14.26 if ((status >= 200 && status < 300) || 304 === status) { return fresh(this.headers, { - 'etag': res.get('ETag'), - 'last-modified': res.get('Last-Modified') - }) + etag: res.get('ETag'), + 'last-modified': res.get('Last-Modified'), + }); } return false; @@ -482,7 +470,7 @@ defineGetter(req, 'fresh', function(){ * @public */ -defineGetter(req, 'stale', function stale(){ +defineGetter(req, 'stale', function stale() { return !this.fresh; }); @@ -493,7 +481,7 @@ defineGetter(req, 'stale', function stale(){ * @public */ -defineGetter(req, 'xhr', function xhr(){ +defineGetter(req, 'xhr', function xhr() { var val = this.get('X-Requested-With') || ''; return val.toLowerCase() === 'xmlhttprequest'; }); @@ -510,6 +498,6 @@ function defineGetter(obj, name, getter) { Object.defineProperty(obj, name, { configurable: true, enumerable: true, - get: getter + get: getter, }); } diff --git a/lib/response.js b/lib/response.js index 937e9858535..3bd39da530f 100644 --- a/lib/response.js +++ b/lib/response.js @@ -12,17 +12,17 @@ * @private */ -var Buffer = require('safe-buffer').Buffer +var Buffer = require('safe-buffer').Buffer; var contentDisposition = require('content-disposition'); -var createError = require('http-errors') +var createError = require('http-errors'); var encodeUrl = require('encodeurl'); var escapeHtml = require('escape-html'); var http = require('http'); var onFinished = require('on-finished'); -var mime = require('mime-types') +var mime = require('mime-types'); var path = require('path'); var pathIsAbsolute = require('path').isAbsolute; -var statuses = require('statuses') +var statuses = require('statuses'); var merge = require('utils-merge'); var sign = require('cookie-signature').sign; var normalizeType = require('./utils').normalizeType; @@ -39,14 +39,14 @@ var vary = require('vary'); * @public */ -var res = Object.create(http.ServerResponse.prototype) +var res = Object.create(http.ServerResponse.prototype); /** * Module exports. * @public */ -module.exports = res +module.exports = res; /** * Set the HTTP status code for the response. @@ -64,11 +64,15 @@ module.exports = res res.status = function status(code) { // Check if the status code is not an integer if (!Number.isInteger(code)) { - throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`); + throw new TypeError( + `Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`, + ); } // Check if the status code is outside of Node's valid range if (code < 100 || code > 999) { - throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`); + throw new RangeError( + `Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`, + ); } this.statusCode = code; @@ -90,12 +94,18 @@ res.status = function status(code) { * @public */ -res.links = function(links){ +res.links = function (links) { var link = this.get('Link') || ''; if (link) link += ', '; - return this.set('Link', link + Object.keys(links).map(function(rel){ - return '<' + links[rel] + '>; rel="' + rel + '"'; - }).join(', ')); + return this.set( + 'Link', + link + + Object.keys(links) + .map(function (rel) { + return '<' + links[rel] + '>; rel="' + rel + '"'; + }) + .join(', '), + ); }; /** @@ -154,23 +164,23 @@ res.send = function send(body) { } // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' + var etagFn = app.get('etag fn'); + var generateETag = !this.get('ETag') && typeof etagFn === 'function'; // populate Content-Length - var len + var len; if (chunk !== undefined) { if (Buffer.isBuffer(chunk)) { // get length of Buffer - len = chunk.length + len = chunk.length; } else if (!generateETag && chunk.length < 1000) { // just calculate length when no ETag + small chunk - len = Buffer.byteLength(chunk, encoding) + len = Buffer.byteLength(chunk, encoding); } else { // convert chunk to Buffer and calculate - chunk = Buffer.from(chunk, encoding) + chunk = Buffer.from(chunk, encoding); encoding = undefined; - len = chunk.length + len = chunk.length; } this.set('Content-Length', len); @@ -197,9 +207,9 @@ res.send = function send(body) { // alter headers for 205 if (this.statusCode === 205) { - this.set('Content-Length', '0') - this.removeHeader('Transfer-Encoding') - chunk = '' + this.set('Content-Length', '0'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; } if (req.method === 'HEAD') { @@ -228,10 +238,10 @@ res.send = function send(body) { res.json = function json(obj) { // settings var app = this.app; - var escape = app.get('json escape') + var escape = app.get('json escape'); var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); - var body = stringify(obj, replacer, spaces, escape) + var body = stringify(obj, replacer, spaces, escape); // content-type if (!this.get('Content-Type')) { @@ -256,10 +266,10 @@ res.json = function json(obj) { res.jsonp = function jsonp(obj) { // settings var app = this.app; - var escape = app.get('json escape') + var escape = app.get('json escape'); var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); - var body = stringify(obj, replacer, spaces, escape) + var body = stringify(obj, replacer, spaces, escape); var callback = this.req.query[app.get('jsonp callback name')]; // content-type @@ -283,17 +293,22 @@ res.jsonp = function jsonp(obj) { if (body === undefined) { // empty argument - body = '' + body = ''; } else if (typeof body === 'string') { // replace chars not allowed in JavaScript that are in JSON - body = body - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029') + body = body.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" // the typeof check is just to reduce client error noise - body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + body = + '/**/ typeof ' + + callback + + " === 'function' && " + + callback + + '(' + + body + + ');'; } return this.send(body); @@ -315,7 +330,7 @@ res.jsonp = function jsonp(obj) { */ res.sendStatus = function sendStatus(statusCode) { - var body = statuses.message[statusCode] || String(statusCode) + var body = statuses.message[statusCode] || String(statusCode); this.status(statusCode); this.type('txt'); @@ -376,7 +391,7 @@ res.sendFile = function sendFile(path, options, callback) { } if (typeof path !== 'string') { - throw new TypeError('path must be a string to res.sendFile') + throw new TypeError('path must be a string to res.sendFile'); } // support function as second arg @@ -386,7 +401,9 @@ res.sendFile = function sendFile(path, options, callback) { } if (!opts.root && !pathIsAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); + throw new TypeError( + 'path must be absolute or specify root to res.sendFile', + ); } // create file stream @@ -423,55 +440,55 @@ res.sendFile = function sendFile(path, options, callback) { * @public */ -res.download = function download (path, filename, options, callback) { +res.download = function download(path, filename, options, callback) { var done = callback; var name = filename; - var opts = options || null + var opts = options || null; // support function as second or third arg if (typeof filename === 'function') { done = filename; name = null; - opts = null + opts = null; } else if (typeof options === 'function') { - done = options - opts = null + done = options; + opts = null; } // support optional filename, where options may be in it's place - if (typeof filename === 'object' && - (typeof options === 'function' || options === undefined)) { - name = null - opts = filename + if ( + typeof filename === 'object' && + (typeof options === 'function' || options === undefined) + ) { + name = null; + opts = filename; } // set Content-Disposition when file is sent var headers = { - 'Content-Disposition': contentDisposition(name || path) + 'Content-Disposition': contentDisposition(name || path), }; // merge user-provided headers if (opts && opts.headers) { - var keys = Object.keys(opts.headers) + var keys = Object.keys(opts.headers); for (var i = 0; i < keys.length; i++) { - var key = keys[i] + var key = keys[i]; if (key.toLowerCase() !== 'content-disposition') { - headers[key] = opts.headers[key] + headers[key] = opts.headers[key]; } } } // merge user-provided options - opts = Object.create(opts) - opts.headers = headers + opts = Object.create(opts); + opts.headers = headers; // Resolve the full path for sendFile - var fullPath = !opts.root - ? resolve(path) - : path + var fullPath = !opts.root ? resolve(path) : path; // send file - return this.sendFile(fullPath, opts, done) + return this.sendFile(fullPath, opts, done); }; /** @@ -493,11 +510,11 @@ res.download = function download (path, filename, options, callback) { * @public */ -res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 - ? (mime.contentType(type) || 'application/octet-stream') - : type; +res.contentType = res.type = function contentType(type) { + var ct = + type.indexOf('/') === -1 + ? mime.contentType(type) || 'application/octet-stream' + : type; return this.set('Content-Type', ct); }; @@ -559,28 +576,31 @@ res.type = function contentType(type) { * @public */ -res.format = function(obj){ +res.format = function (obj) { var req = this.req; var next = req.next; - var keys = Object.keys(obj) - .filter(function (v) { return v !== 'default' }) + var keys = Object.keys(obj).filter(function (v) { + return v !== 'default'; + }); - var key = keys.length > 0 - ? req.accepts(keys) - : false; + var key = keys.length > 0 ? req.accepts(keys) : false; - this.vary("Accept"); + this.vary('Accept'); if (key) { this.set('Content-Type', normalizeType(key).value); obj[key](req, this, next); } else if (obj.default) { - obj.default(req, this, next) + obj.default(req, this, next); } else { - next(createError(406, { - types: normalizeTypes(keys).map(function (o) { return o.value }) - })) + next( + createError(406, { + types: normalizeTypes(keys).map(function (o) { + return o.value; + }), + }), + ); } return this; @@ -625,9 +645,11 @@ res.append = function append(field, val) { if (prev) { // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) - : [prev, val] + value = Array.isArray(prev) + ? prev.concat(val) + : Array.isArray(val) + ? [prev].concat(val) + : [prev, val]; } return this.set(field, value); @@ -654,19 +676,16 @@ res.append = function append(field, val) { * @public */ -res.set = -res.header = function header(field, val) { +res.set = res.header = function header(field, val) { if (arguments.length === 2) { - var value = Array.isArray(val) - ? val.map(String) - : String(val); + var value = Array.isArray(val) ? val.map(String) : String(val); // add charset to content-type if (field.toLowerCase() === 'content-type') { if (Array.isArray(value)) { throw new TypeError('Content-Type cannot be set to an Array'); } - value = mime.contentType(value) + value = mime.contentType(value); } this.setHeader(field, value); @@ -686,7 +705,7 @@ res.header = function header(field, val) { * @public */ -res.get = function(field){ +res.get = function (field) { return this.getHeader(field); }; @@ -701,9 +720,9 @@ res.get = function(field){ res.clearCookie = function clearCookie(name, options) { // Force cookie expiration by setting expires to the past - const opts = { path: '/', ...options, expires: new Date(1)}; + const opts = { path: '/', ...options, expires: new Date(1) }; // ensure maxAge is not passed - delete opts.maxAge + delete opts.maxAge; return this.cookie(name, '', opts); }; @@ -741,20 +760,19 @@ res.cookie = function (name, value, options) { throw new Error('cookieParser("secret") required for signed cookies'); } - var val = typeof value === 'object' - ? 'j:' + JSON.stringify(value) - : String(value); + var val = + typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value); if (signed) { val = 's:' + sign(val, secret); } if (opts.maxAge != null) { - var maxAge = opts.maxAge - 0 + var maxAge = opts.maxAge - 0; if (!isNaN(maxAge)) { - opts.expires = new Date(Date.now() + maxAge) - opts.maxAge = Math.floor(maxAge / 1000) + opts.expires = new Date(Date.now() + maxAge); + opts.maxAge = Math.floor(maxAge / 1000); } } @@ -809,8 +827,8 @@ res.redirect = function redirect(url) { // allow status / url if (arguments.length === 2) { - status = arguments[0] - address = arguments[1] + status = arguments[0]; + address = arguments[1]; } // Set location header @@ -818,18 +836,19 @@ res.redirect = function redirect(url) { // Support text/{plain,html} by default this.format({ - text: function(){ - body = statuses.message[status] + '. Redirecting to ' + address + text: function () { + body = statuses.message[status] + '. Redirecting to ' + address; }, - html: function(){ + html: function () { var u = escapeHtml(address); - body = '

' + statuses.message[status] + '. Redirecting to ' + u + '

' + body = + '

' + statuses.message[status] + '. Redirecting to ' + u + '

'; }, - default: function(){ + default: function () { body = ''; - } + }, }); // Respond @@ -852,7 +871,7 @@ res.redirect = function redirect(url) { * @public */ -res.vary = function(field){ +res.vary = function (field) { vary(this, field); return this; @@ -888,10 +907,12 @@ res.render = function render(view, options, callback) { opts._locals = self.locals; // default callback to respond - done = done || function (err, str) { - if (err) return req.next(err); - self.send(str); - }; + done = + done || + function (err, str) { + if (err) return req.next(err); + self.send(str); + }; // render app.render(view, opts, done); @@ -1000,28 +1021,29 @@ function sendfile(res, file, options, callback) { * @private */ -function stringify (value, replacer, spaces, escape) { +function stringify(value, replacer, spaces, escape) { // v8 checks arguments.length for optimizing simple call // https://bugs.chromium.org/p/v8/issues/detail?id=4730 - var json = replacer || spaces - ? JSON.stringify(value, replacer, spaces) - : JSON.stringify(value); + var json = + replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); if (escape && typeof json === 'string') { json = json.replace(/[<>&]/g, function (c) { switch (c.charCodeAt(0)) { case 0x3c: - return '\\u003c' + return '\\u003c'; case 0x3e: - return '\\u003e' + return '\\u003e'; case 0x26: - return '\\u0026' + return '\\u0026'; /* istanbul ignore next: unreachable default */ default: - return c + return c; } - }) + }); } - return json + return json; } diff --git a/lib/utils.js b/lib/utils.js index f66760a17c0..23b7f79dc6e 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -12,10 +12,10 @@ * @api private */ -var Buffer = require('safe-buffer').Buffer +var Buffer = require('safe-buffer').Buffer; var contentType = require('content-type'); var etag = require('etag'); -var mime = require('mime-types') +var mime = require('mime-types'); var proxyaddr = require('proxy-addr'); var qs = require('qs'); var querystring = require('querystring'); @@ -29,7 +29,7 @@ var querystring = require('querystring'); * @api private */ -exports.etag = createETagGenerator({ weak: false }) +exports.etag = createETagGenerator({ weak: false }); /** * Return weak ETag for `body`. @@ -40,7 +40,7 @@ exports.etag = createETagGenerator({ weak: false }) * @api private */ -exports.wetag = createETagGenerator({ weak: true }) +exports.wetag = createETagGenerator({ weak: true }); /** * Normalize the given `type`, for example "html" becomes "text/html". @@ -50,10 +50,10 @@ exports.wetag = createETagGenerator({ weak: true }) * @api private */ -exports.normalizeType = function(type){ +exports.normalizeType = function (type) { return ~type.indexOf('/') ? acceptParams(type) - : { value: (mime.lookup(type) || 'application/octet-stream'), params: {} } + : { value: mime.lookup(type) || 'application/octet-stream', params: {} }; }; /** @@ -64,7 +64,7 @@ exports.normalizeType = function(type){ * @api private */ -exports.normalizeTypes = function(types){ +exports.normalizeTypes = function (types) { var ret = []; for (var i = 0; i < types.length; ++i) { @@ -83,9 +83,9 @@ exports.normalizeTypes = function(types){ * @api private */ -function acceptParams (str) { +function acceptParams(str) { var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {} } + var ret = { value: parts[0], quality: 1, params: {} }; for (var i = 1; i < parts.length; ++i) { var pms = parts[i].split(/ *= */); @@ -107,7 +107,7 @@ function acceptParams (str) { * @api private */ -exports.compileETag = function(val) { +exports.compileETag = function (val) { var fn; if (typeof val === 'function') { @@ -129,7 +129,7 @@ exports.compileETag = function(val) { } return fn; -} +}; /** * Compile "query parser" value to function. @@ -161,7 +161,7 @@ exports.compileQueryParser = function compileQueryParser(val) { } return fn; -} +}; /** * Compile "proxy trust" value to function. @@ -171,27 +171,32 @@ exports.compileQueryParser = function compileQueryParser(val) { * @api private */ -exports.compileTrust = function(val) { +exports.compileTrust = function (val) { if (typeof val === 'function') return val; if (val === true) { // Support plain true/false - return function(){ return true }; + return function () { + return true; + }; } if (typeof val === 'number') { // Support trusting hop count - return function(a, i){ return i < val }; + return function (a, i) { + return i < val; + }; } if (typeof val === 'string') { // Support comma-separated values - val = val.split(',') - .map(function (v) { return v.trim() }) + val = val.split(',').map(function (v) { + return v.trim(); + }); } return proxyaddr.compile(val || []); -} +}; /** * Set the charset in a given Content-Type string. @@ -226,14 +231,12 @@ exports.setCharset = function setCharset(type, charset) { * @private */ -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body +function createETagGenerator(options) { + return function generateETag(body, encoding) { + var buf = !Buffer.isBuffer(body) ? Buffer.from(body, encoding) : body; - return etag(buf, options) - } + return etag(buf, options); + }; } /** @@ -246,6 +249,6 @@ function createETagGenerator (options) { function parseExtendedQueryString(str) { return qs.parse(str, { - allowPrototypes: true + allowPrototypes: true, }); } diff --git a/lib/view.js b/lib/view.js index 6beffca6e24..16357bec617 100644 --- a/lib/view.js +++ b/lib/view.js @@ -58,33 +58,36 @@ function View(name, options) { this.root = opts.root; if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); + throw new Error( + 'No default engine was specified and no extension was provided.', + ); } var fileName = name; if (!this.ext) { // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; + this.ext = + this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; fileName += this.ext; } if (!opts.engines[this.ext]) { // load engine - var mod = this.ext.slice(1) - debug('require "%s"', mod) + var mod = this.ext.slice(1); + debug('require "%s"', mod); // default engine export - var fn = require(mod).__express + var fn = require(mod).__express; if (typeof fn !== 'function') { - throw new Error('Module "' + mod + '" does not provide a view engine.') + throw new Error('Module "' + mod + '" does not provide a view engine.'); } - opts.engines[this.ext] = fn + opts.engines[this.ext] = fn; } // store loaded engine diff --git a/package.json b/package.json index a23e46022ee..66ec9f63ccc 100644 --- a/package.json +++ b/package.json @@ -79,6 +79,7 @@ "morgan": "1.10.0", "nyc": "15.1.0", "pbkdf2-password": "1.2.1", + "prettier": "^3.3.3", "supertest": "6.3.0", "vhost": "~3.0.2" }, @@ -93,6 +94,7 @@ "lib/" ], "scripts": { + "format": "prettier --write \"**/*.js\"", "lint": "eslint .", "test": "mocha --require test/support/env --reporter spec --check-leaks test/ test/acceptance/", "test-ci": "nyc --exclude examples --exclude test --exclude benchmarks --reporter=lcovonly --reporter=text npm test", diff --git a/test/Route.js b/test/Route.js index 2a37b9a4839..a8d801fefbf 100644 --- a/test/Route.js +++ b/test/Route.js @@ -1,76 +1,76 @@ -'use strict' +'use strict'; var after = require('after'); -var assert = require('assert') -var express = require('../') - , Route = express.Route - , methods = require('methods') - -describe('Route', function(){ - it('should work without handlers', function(done) { - var req = { method: 'GET', url: '/' } - var route = new Route('/foo') - route.dispatch(req, {}, done) - }) +var assert = require('assert'); +var express = require('../'), + Route = express.Route, + methods = require('methods'); + +describe('Route', function () { + it('should work without handlers', function (done) { + var req = { method: 'GET', url: '/' }; + var route = new Route('/foo'); + route.dispatch(req, {}, done); + }); it('should not stack overflow with a large sync stack', function (done) { - this.timeout(5000) // long-running test + this.timeout(5000); // long-running test - var req = { method: 'GET', url: '/' } - var route = new Route('/foo') + var req = { method: 'GET', url: '/' }; + var route = new Route('/foo'); route.get(function (req, res, next) { - req.counter = 0 - next() - }) + req.counter = 0; + next(); + }); for (var i = 0; i < 6000; i++) { route.all(function (req, res, next) { - req.counter++ - next() - }) + req.counter++; + next(); + }); } route.get(function (req, res, next) { - req.called = true - next() - }) + req.called = true; + next(); + }); route.dispatch(req, {}, function (err) { - if (err) return done(err) - assert.ok(req.called) - assert.strictEqual(req.counter, 6000) - done() - }) - }) - - describe('.all', function(){ - it('should add handler', function(done){ + if (err) return done(err); + assert.ok(req.called); + assert.strictEqual(req.counter, 6000); + done(); + }); + }); + + describe('.all', function () { + it('should add handler', function (done) { var req = { method: 'GET', url: '/' }; var route = new Route('/foo'); - route.all(function(req, res, next) { + route.all(function (req, res, next) { req.called = true; next(); }); route.dispatch(req, {}, function (err) { if (err) return done(err); - assert.ok(req.called) + assert.ok(req.called); done(); }); - }) + }); - it('should handle VERBS', function(done) { + it('should handle VERBS', function (done) { var count = 0; var route = new Route('/foo'); var cb = after(methods.length, function (err) { if (err) return done(err); - assert.strictEqual(count, methods.length) + assert.strictEqual(count, methods.length); done(); }); - route.all(function(req, res, next) { + route.all(function (req, res, next) { count++; next(); }); @@ -79,122 +79,122 @@ describe('Route', function(){ var req = { method: method, url: '/' }; route.dispatch(req, {}, cb); }); - }) + }); - it('should stack', function(done) { + it('should stack', function (done) { var req = { count: 0, method: 'GET', url: '/' }; var route = new Route('/foo'); - route.all(function(req, res, next) { + route.all(function (req, res, next) { req.count++; next(); }); - route.all(function(req, res, next) { + route.all(function (req, res, next) { req.count++; next(); }); route.dispatch(req, {}, function (err) { if (err) return done(err); - assert.strictEqual(req.count, 2) + assert.strictEqual(req.count, 2); done(); }); - }) - }) + }); + }); - describe('.VERB', function(){ - it('should support .get', function(done){ + describe('.VERB', function () { + it('should support .get', function (done) { var req = { method: 'GET', url: '/' }; var route = new Route(''); - route.get(function(req, res, next) { + route.get(function (req, res, next) { req.called = true; next(); - }) + }); route.dispatch(req, {}, function (err) { if (err) return done(err); - assert.ok(req.called) + assert.ok(req.called); done(); }); - }) + }); - it('should limit to just .VERB', function(done){ + it('should limit to just .VERB', function (done) { var req = { method: 'POST', url: '/' }; var route = new Route(''); route.get(function () { throw new Error('not me!'); - }) + }); - route.post(function(req, res, next) { + route.post(function (req, res, next) { req.called = true; next(); - }) + }); route.dispatch(req, {}, function (err) { if (err) return done(err); - assert.ok(req.called) + assert.ok(req.called); done(); }); - }) + }); - it('should allow fallthrough', function(done){ + it('should allow fallthrough', function (done) { var req = { order: '', method: 'GET', url: '/' }; var route = new Route(''); - route.get(function(req, res, next) { + route.get(function (req, res, next) { req.order += 'a'; next(); - }) + }); - route.all(function(req, res, next) { + route.all(function (req, res, next) { req.order += 'b'; next(); }); - route.get(function(req, res, next) { + route.get(function (req, res, next) { req.order += 'c'; next(); - }) + }); route.dispatch(req, {}, function (err) { if (err) return done(err); - assert.strictEqual(req.order, 'abc') + assert.strictEqual(req.order, 'abc'); done(); }); - }) - }) + }); + }); - describe('errors', function(){ - it('should handle errors via arity 4 functions', function(done){ + describe('errors', function () { + it('should handle errors via arity 4 functions', function (done) { var req = { order: '', method: 'GET', url: '/' }; var route = new Route(''); - route.all(function(req, res, next){ + route.all(function (req, res, next) { next(new Error('foobar')); }); - route.all(function(req, res, next){ + route.all(function (req, res, next) { req.order += '0'; next(); }); - route.all(function(err, req, res, next){ + route.all(function (err, req, res, next) { req.order += 'a'; next(err); }); route.dispatch(req, {}, function (err) { - assert.ok(err) - assert.strictEqual(err.message, 'foobar') - assert.strictEqual(req.order, 'a') + assert.ok(err); + assert.strictEqual(err.message, 'foobar'); + assert.strictEqual(req.order, 'a'); done(); }); - }) + }); - it('should handle throw', function(done) { + it('should handle throw', function (done) { var req = { order: '', method: 'GET', url: '/' }; var route = new Route(''); @@ -202,25 +202,25 @@ describe('Route', function(){ throw new Error('foobar'); }); - route.all(function(req, res, next){ + route.all(function (req, res, next) { req.order += '0'; next(); }); - route.all(function(err, req, res, next){ + route.all(function (err, req, res, next) { req.order += 'a'; next(err); }); route.dispatch(req, {}, function (err) { - assert.ok(err) - assert.strictEqual(err.message, 'foobar') - assert.strictEqual(req.order, 'a') + assert.ok(err); + assert.strictEqual(err.message, 'foobar'); + assert.strictEqual(req.order, 'a'); done(); }); }); - it('should handle throwing inside error handlers', function(done) { + it('should handle throwing inside error handlers', function (done) { var req = { method: 'GET', url: '/' }; var route = new Route(''); @@ -228,47 +228,47 @@ describe('Route', function(){ throw new Error('boom!'); }); - route.get(function(err, req, res, next){ + route.get(function (err, req, res, next) { throw new Error('oops'); }); - route.get(function(err, req, res, next){ + route.get(function (err, req, res, next) { req.message = err.message; next(); }); route.dispatch(req, {}, function (err) { if (err) return done(err); - assert.strictEqual(req.message, 'oops') + assert.strictEqual(req.message, 'oops'); done(); }); }); - it('should handle throw in .all', function(done) { + it('should handle throw in .all', function (done) { var req = { method: 'GET', url: '/' }; var route = new Route(''); - route.all(function(req, res, next){ + route.all(function (req, res, next) { throw new Error('boom!'); }); - route.dispatch(req, {}, function(err){ - assert.ok(err) - assert.strictEqual(err.message, 'boom!') + route.dispatch(req, {}, function (err) { + assert.ok(err); + assert.strictEqual(err.message, 'boom!'); done(); }); }); - it('should handle single error handler', function(done) { + it('should handle single error handler', function (done) { var req = { method: 'GET', url: '/' }; var route = new Route(''); - route.all(function(err, req, res, next){ + route.all(function (err, req, res, next) { // this should not execute - throw new Error('should not be called') + throw new Error('should not be called'); }); route.dispatch(req, {}, done); }); - }) -}) + }); +}); diff --git a/test/Router.js b/test/Router.js index a1952f445ac..bd8decd6ccf 100644 --- a/test/Router.js +++ b/test/Router.js @@ -1,227 +1,250 @@ -'use strict' +'use strict'; var after = require('after'); -var express = require('../') - , Router = express.Router - , methods = require('methods') - , assert = require('assert'); +var express = require('../'), + Router = express.Router, + methods = require('methods'), + assert = require('assert'); -describe('Router', function(){ - it('should return a function with router methods', function() { +describe('Router', function () { + it('should return a function with router methods', function () { var router = new Router(); - assert(typeof router === 'function') + assert(typeof router === 'function'); - assert(typeof router.get === 'function') - assert(typeof router.handle === 'function') - assert(typeof router.use === 'function') + assert(typeof router.get === 'function'); + assert(typeof router.handle === 'function'); + assert(typeof router.use === 'function'); }); - it('should support .use of other routers', function(done){ + it('should support .use of other routers', function (done) { var router = new Router(); var another = new Router(); - another.get('/bar', function(req, res){ + another.get('/bar', function (req, res) { res.end(); }); router.use('/foo', another); - router.handle({ url: '/foo/bar', method: 'GET' }, { end: done }, function(){}); + router.handle( + { url: '/foo/bar', method: 'GET' }, + { end: done }, + function () {}, + ); }); - it('should support dynamic routes', function(done){ + it('should support dynamic routes', function (done) { var router = new Router(); var another = new Router(); - another.get('/:bar', function(req, res){ - assert.strictEqual(req.params.bar, 'route') + another.get('/:bar', function (req, res) { + assert.strictEqual(req.params.bar, 'route'); res.end(); }); router.use('/:foo', another); - router.handle({ url: '/test/route', method: 'GET' }, { end: done }, function(){}); + router.handle( + { url: '/test/route', method: 'GET' }, + { end: done }, + function () {}, + ); }); - it('should handle blank URL', function(done){ + it('should handle blank URL', function (done) { var router = new Router(); router.use(function (req, res) { - throw new Error('should not be called') + throw new Error('should not be called'); }); router.handle({ url: '', method: 'GET' }, {}, done); }); it('should handle missing URL', function (done) { - var router = new Router() + var router = new Router(); router.use(function (req, res) { - throw new Error('should not be called') - }) + throw new Error('should not be called'); + }); - router.handle({ method: 'GET' }, {}, done) - }) + router.handle({ method: 'GET' }, {}, done); + }); it('handle missing method', function (done) { - var all = false - var router = new Router() - var route = router.route('/foo') - var use = false + var all = false; + var router = new Router(); + var route = router.route('/foo'); + var use = false; - route.post(function (req, res, next) { next(new Error('should not run')) }) + route.post(function (req, res, next) { + next(new Error('should not run')); + }); route.all(function (req, res, next) { - all = true - next() - }) - route.get(function (req, res, next) { next(new Error('should not run')) }) + all = true; + next(); + }); + route.get(function (req, res, next) { + next(new Error('should not run')); + }); - router.get('/foo', function (req, res, next) { next(new Error('should not run')) }) + router.get('/foo', function (req, res, next) { + next(new Error('should not run')); + }); router.use(function (req, res, next) { - use = true - next() - }) + use = true; + next(); + }); router.handle({ url: '/foo' }, {}, function (err) { - if (err) return done(err) - assert.ok(all) - assert.ok(use) - done() - }) - }) + if (err) return done(err); + assert.ok(all); + assert.ok(use); + done(); + }); + }); - it('should not stack overflow with many registered routes', function(done){ - this.timeout(5000) // long-running test + it('should not stack overflow with many registered routes', function (done) { + this.timeout(5000); // long-running test - var handler = function(req, res){ res.end(new Error('wrong handler')) }; + var handler = function (req, res) { + res.end(new Error('wrong handler')); + }; var router = new Router(); for (var i = 0; i < 6000; i++) { - router.get('/thing' + i, handler) + router.get('/thing' + i, handler); } router.get('/', function (req, res) { res.end(); }); - router.handle({ url: '/', method: 'GET' }, { end: done }, function(){}); + router.handle({ url: '/', method: 'GET' }, { end: done }, function () {}); }); it('should not stack overflow with a large sync route stack', function (done) { - this.timeout(5000) // long-running test + this.timeout(5000); // long-running test - var router = new Router() + var router = new Router(); router.get('/foo', function (req, res, next) { - req.counter = 0 - next() - }) + req.counter = 0; + next(); + }); for (var i = 0; i < 6000; i++) { router.get('/foo', function (req, res, next) { - req.counter++ - next() - }) + req.counter++; + next(); + }); } router.get('/foo', function (req, res) { - assert.strictEqual(req.counter, 6000) - res.end() - }) - - router.handle({ url: '/foo', method: 'GET' }, { end: done }, function (err) { - assert(!err, err); + assert.strictEqual(req.counter, 6000); + res.end(); }); - }) + + router.handle( + { url: '/foo', method: 'GET' }, + { end: done }, + function (err) { + assert(!err, err); + }, + ); + }); it('should not stack overflow with a large sync middleware stack', function (done) { - this.timeout(5000) // long-running test + this.timeout(5000); // long-running test - var router = new Router() + var router = new Router(); router.use(function (req, res, next) { - req.counter = 0 - next() - }) + req.counter = 0; + next(); + }); for (var i = 0; i < 6000; i++) { router.use(function (req, res, next) { - req.counter++ - next() - }) + req.counter++; + next(); + }); } router.use(function (req, res) { - assert.strictEqual(req.counter, 6000) - res.end() - }) + assert.strictEqual(req.counter, 6000); + res.end(); + }); router.handle({ url: '/', method: 'GET' }, { end: done }, function (err) { assert(!err, err); - }) - }) + }); + }); - describe('.handle', function(){ - it('should dispatch', function(done){ + describe('.handle', function () { + it('should dispatch', function (done) { var router = new Router(); - router.route('/foo').get(function(req, res){ + router.route('/foo').get(function (req, res) { res.send('foo'); }); var res = { - send: function(val) { - assert.strictEqual(val, 'foo') + send: function (val) { + assert.strictEqual(val, 'foo'); done(); - } - } - router.handle({ url: '/foo', method: 'GET' }, res, function(){}); - }) - }) + }, + }; + router.handle({ url: '/foo', method: 'GET' }, res, function () {}); + }); + }); - describe('.multiple callbacks', function(){ - it('should throw if a callback is null', function(){ + describe('.multiple callbacks', function () { + it('should throw if a callback is null', function () { assert.throws(function () { var router = new Router(); router.route('/foo').all(null); - }) - }) + }); + }); - it('should throw if a callback is undefined', function(){ + it('should throw if a callback is undefined', function () { assert.throws(function () { var router = new Router(); router.route('/foo').all(undefined); - }) - }) + }); + }); - it('should throw if a callback is not a function', function(){ + it('should throw if a callback is not a function', function () { assert.throws(function () { var router = new Router(); router.route('/foo').all('not a function'); - }) - }) + }); + }); - it('should not throw if all callbacks are functions', function(){ + it('should not throw if all callbacks are functions', function () { var router = new Router(); - router.route('/foo').all(function(){}).all(function(){}); - }) - }) + router + .route('/foo') + .all(function () {}) + .all(function () {}); + }); + }); - describe('error', function(){ - it('should skip non error middleware', function(done){ + describe('error', function () { + it('should skip non error middleware', function (done) { var router = new Router(); - router.get('/foo', function(req, res, next){ + router.get('/foo', function (req, res, next) { next(new Error('foo')); }); - router.get('/bar', function(req, res, next){ + router.get('/bar', function (req, res, next) { next(new Error('bar')); }); - router.use(function(req, res, next){ + router.use(function (req, res, next) { assert(false); }); - router.use(function(err, req, res, next){ + router.use(function (err, req, res, next) { assert.equal(err.message, 'foo'); done(); }); @@ -229,66 +252,66 @@ describe('Router', function(){ router.handle({ url: '/foo', method: 'GET' }, {}, done); }); - it('should handle throwing inside routes with params', function(done) { + it('should handle throwing inside routes with params', function (done) { var router = new Router(); router.get('/foo/:id', function () { throw new Error('foo'); }); - router.use(function(req, res, next){ + router.use(function (req, res, next) { assert(false); }); - router.use(function(err, req, res, next){ + router.use(function (err, req, res, next) { assert.equal(err.message, 'foo'); done(); }); - router.handle({ url: '/foo/2', method: 'GET' }, {}, function() {}); + router.handle({ url: '/foo/2', method: 'GET' }, {}, function () {}); }); - it('should handle throwing in handler after async param', function(done) { + it('should handle throwing in handler after async param', function (done) { var router = new Router(); - router.param('user', function(req, res, next, val){ - process.nextTick(function(){ + router.param('user', function (req, res, next, val) { + process.nextTick(function () { req.user = val; next(); }); }); - router.use('/:user', function(req, res, next){ + router.use('/:user', function (req, res, next) { throw new Error('oh no!'); }); - router.use(function(err, req, res, next){ + router.use(function (err, req, res, next) { assert.equal(err.message, 'oh no!'); done(); }); - router.handle({ url: '/bob', method: 'GET' }, {}, function() {}); + router.handle({ url: '/bob', method: 'GET' }, {}, function () {}); }); - it('should handle throwing inside error handlers', function(done) { + it('should handle throwing inside error handlers', function (done) { var router = new Router(); - router.use(function(req, res, next){ + router.use(function (req, res, next) { throw new Error('boom!'); }); - router.use(function(err, req, res, next){ + router.use(function (err, req, res, next) { throw new Error('oops'); }); - router.use(function(err, req, res, next){ + router.use(function (err, req, res, next) { assert.equal(err.message, 'oops'); done(); }); router.handle({ url: '/', method: 'GET' }, {}, done); }); - }) + }); describe('FQDN', function () { it('should not obscure FQDNs', function (done) { @@ -309,7 +332,11 @@ describe('Router', function(){ }); it('should ignore FQDN in search', function (done) { - var request = { hit: 0, url: '/proxy?url=http://example.com/blog/post/1', method: 'GET' }; + var request = { + hit: 0, + url: '/proxy?url=http://example.com/blog/post/1', + method: 'GET', + }; var router = new Router(); router.use('/proxy', function (req, res, next) { @@ -326,7 +353,11 @@ describe('Router', function(){ }); it('should ignore FQDN in path', function (done) { - var request = { hit: 0, url: '/proxy/http://example.com/blog/post/1', method: 'GET' }; + var request = { + hit: 0, + url: '/proxy/http://example.com/blog/post/1', + method: 'GET', + }; var router = new Router(); router.use('/proxy', function (req, res, next) { @@ -343,7 +374,11 @@ describe('Router', function(){ }); it('should adjust FQDN req.url', function (done) { - var request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' }; + var request = { + hit: 0, + url: 'http://example.com/blog/post/1', + method: 'GET', + }; var router = new Router(); router.use('/blog', function (req, res, next) { @@ -360,7 +395,11 @@ describe('Router', function(){ }); it('should adjust FQDN req.url with multiple handlers', function (done) { - var request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' }; + var request = { + hit: 0, + url: 'http://example.com/blog/post/1', + method: 'GET', + }; var router = new Router(); router.use(function (req, res, next) { @@ -383,7 +422,11 @@ describe('Router', function(){ }); it('should adjust FQDN req.url with multiple routed handlers', function (done) { - var request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' }; + var request = { + hit: 0, + url: 'http://example.com/blog/post/1', + method: 'GET', + }; var router = new Router(); router.use('/blog', function (req, res, next) { @@ -410,94 +453,106 @@ describe('Router', function(){ done(); }); }); - }) + }); - describe('.all', function() { - it('should support using .all to capture all http verbs', function(done){ + describe('.all', function () { + it('should support using .all to capture all http verbs', function (done) { var router = new Router(); var count = 0; - router.all('/foo', function(){ count++; }); + router.all('/foo', function () { + count++; + }); var url = '/foo?bar=baz'; methods.forEach(function testMethod(method) { - router.handle({ url: url, method: method }, {}, function() {}); + router.handle({ url: url, method: method }, {}, function () {}); }); assert.equal(count, methods.length); done(); - }) - }) + }); + }); - describe('.use', function() { + describe('.use', function () { it('should require middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/') }, /argument handler is required/) - }) + var router = new Router(); + assert.throws(function () { + router.use('/'); + }, /argument handler is required/); + }); it('should reject string as middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/', 'foo') }, /argument handler must be a function/) - }) + var router = new Router(); + assert.throws(function () { + router.use('/', 'foo'); + }, /argument handler must be a function/); + }); it('should reject number as middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/', 42) }, /argument handler must be a function/) - }) + var router = new Router(); + assert.throws(function () { + router.use('/', 42); + }, /argument handler must be a function/); + }); it('should reject null as middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/', null) }, /argument handler must be a function/) - }) + var router = new Router(); + assert.throws(function () { + router.use('/', null); + }, /argument handler must be a function/); + }); it('should reject Date as middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/', new Date()) }, /argument handler must be a function/) - }) + var router = new Router(); + assert.throws(function () { + router.use('/', new Date()); + }, /argument handler must be a function/); + }); it('should be called for any URL', function (done) { - var cb = after(4, done) - var router = new Router() + var cb = after(4, done); + var router = new Router(); - function no () { - throw new Error('should not be called') + function no() { + throw new Error('should not be called'); } router.use(function (req, res) { - res.end() - }) + res.end(); + }); - router.handle({ url: '/', method: 'GET' }, { end: cb }, no) - router.handle({ url: '/foo', method: 'GET' }, { end: cb }, no) - router.handle({ url: 'foo', method: 'GET' }, { end: cb }, no) - router.handle({ url: '*', method: 'GET' }, { end: cb }, no) - }) + router.handle({ url: '/', method: 'GET' }, { end: cb }, no); + router.handle({ url: '/foo', method: 'GET' }, { end: cb }, no); + router.handle({ url: 'foo', method: 'GET' }, { end: cb }, no); + router.handle({ url: '*', method: 'GET' }, { end: cb }, no); + }); - it('should accept array of middleware', function(done){ + it('should accept array of middleware', function (done) { var count = 0; var router = new Router(); - function fn1(req, res, next){ + function fn1(req, res, next) { assert.equal(++count, 1); next(); } - function fn2(req, res, next){ + function fn2(req, res, next) { assert.equal(++count, 2); next(); } - router.use([fn1, fn2], function(req, res){ + router.use([fn1, fn2], function (req, res) { assert.equal(++count, 3); done(); }); - router.handle({ url: '/foo', method: 'GET' }, {}, function(){}); - }) - }) + router.handle({ url: '/foo', method: 'GET' }, {}, function () {}); + }); + }); - describe('.param', function() { + describe('.param', function () { it('should require function', function () { var router = new Router(); assert.throws(router.param.bind(router, 'id'), /argument fn is required/); @@ -505,18 +560,21 @@ describe('Router', function(){ it('should reject non-function', function () { var router = new Router(); - assert.throws(router.param.bind(router, 'id', 42), /argument fn must be a function/); + assert.throws( + router.param.bind(router, 'id', 42), + /argument fn must be a function/, + ); }); - it('should call param function when routing VERBS', function(done) { + it('should call param function when routing VERBS', function (done) { var router = new Router(); - router.param('id', function(req, res, next, id) { + router.param('id', function (req, res, next, id) { assert.equal(id, '123'); next(); }); - router.get('/foo/:id/bar', function(req, res, next) { + router.get('/foo/:id/bar', function (req, res, next) { assert.equal(req.params.id, '123'); next(); }); @@ -524,15 +582,15 @@ describe('Router', function(){ router.handle({ url: '/foo/123/bar', method: 'get' }, {}, done); }); - it('should call param function when routing middleware', function(done) { + it('should call param function when routing middleware', function (done) { var router = new Router(); - router.param('id', function(req, res, next, id) { + router.param('id', function (req, res, next, id) { assert.equal(id, '123'); next(); }); - router.use('/foo/:id/bar', function(req, res, next) { + router.use('/foo/:id/bar', function (req, res, next) { assert.equal(req.params.id, '123'); assert.equal(req.url, '/baz'); next(); @@ -541,17 +599,17 @@ describe('Router', function(){ router.handle({ url: '/foo/123/bar/baz', method: 'get' }, {}, done); }); - it('should only call once per request', function(done) { + it('should only call once per request', function (done) { var count = 0; var req = { url: '/foo/bob/bar', method: 'get' }; var router = new Router(); var sub = new Router(); - sub.get('/bar', function(req, res, next) { + sub.get('/bar', function (req, res, next) { next(); }); - router.param('user', function(req, res, next, user) { + router.param('user', function (req, res, next, user) { count++; req.user = user; next(); @@ -560,7 +618,7 @@ describe('Router', function(){ router.use('/foo/:user/', new Router()); router.use('/foo/:user/', sub); - router.handle(req, {}, function(err) { + router.handle(req, {}, function (err) { if (err) return done(err); assert.equal(count, 1); assert.equal(req.user, 'bob'); @@ -568,17 +626,17 @@ describe('Router', function(){ }); }); - it('should call when values differ', function(done) { + it('should call when values differ', function (done) { var count = 0; var req = { url: '/foo/bob/bar', method: 'get' }; var router = new Router(); var sub = new Router(); - sub.get('/bar', function(req, res, next) { + sub.get('/bar', function (req, res, next) { next(); }); - router.param('user', function(req, res, next, user) { + router.param('user', function (req, res, next, user) { count++; req.user = user; next(); @@ -587,7 +645,7 @@ describe('Router', function(){ router.use('/foo/:user/', new Router()); router.use('/:user/bob/', sub); - router.handle(req, {}, function(err) { + router.handle(req, {}, function (err) { if (err) return done(err); assert.equal(count, 2); assert.equal(req.user, 'foo'); @@ -596,20 +654,19 @@ describe('Router', function(){ }); }); - describe('parallel requests', function() { - it('should not mix requests', function(done) { + describe('parallel requests', function () { + it('should not mix requests', function (done) { var req1 = { url: '/foo/50/bar', method: 'get' }; var req2 = { url: '/foo/10/bar', method: 'get' }; var router = new Router(); var sub = new Router(); - var cb = after(2, done) - + var cb = after(2, done); - sub.get('/bar', function(req, res, next) { + sub.get('/bar', function (req, res, next) { next(); }); - router.param('ms', function(req, res, next, ms) { + router.param('ms', function (req, res, next, ms) { ms = parseInt(ms, 10); req.ms = ms; setTimeout(next, ms); @@ -618,19 +675,19 @@ describe('Router', function(){ router.use('/foo/:ms/', new Router()); router.use('/foo/:ms/', sub); - router.handle(req1, {}, function(err) { + router.handle(req1, {}, function (err) { assert.ifError(err); assert.equal(req1.ms, 50); assert.equal(req1.originalUrl, '/foo/50/bar'); - cb() + cb(); }); - router.handle(req2, {}, function(err) { + router.handle(req2, {}, function (err) { assert.ifError(err); assert.equal(req2.ms, 10); assert.equal(req2.originalUrl, '/foo/10/bar'); - cb() + cb(); }); }); }); -}) +}); diff --git a/test/acceptance/auth.js b/test/acceptance/auth.js index d7838755a08..877256ec9aa 100644 --- a/test/acceptance/auth.js +++ b/test/acceptance/auth.js @@ -1,41 +1,36 @@ -var app = require('../../examples/auth') -var request = require('supertest') +var app = require('../../examples/auth'); +var request = require('supertest'); function getCookie(res) { return res.headers['set-cookie'][0].split(';')[0]; } -describe('auth', function(){ - describe('GET /',function(){ - it('should redirect to /login', function(done){ - request(app) - .get('/') - .expect('Location', '/login') - .expect(302, done) - }) - }) +describe('auth', function () { + describe('GET /', function () { + it('should redirect to /login', function (done) { + request(app).get('/').expect('Location', '/login').expect(302, done); + }); + }); - describe('GET /login',function(){ - it('should render login form', function(done){ - request(app) - .get('/login') - .expect(200, /
  • Tobi
  • Loki
  • Jane
  • ', done) - }) + .get('/') + .expect(200, '', done); + }); - it('should accept to text/plain', function(done){ + it('should accept to text/plain', function (done) { request(app) - .get('/') - .set('Accept', 'text/plain') - .expect(200, ' - Tobi\n - Loki\n - Jane\n', done) - }) + .get('/') + .set('Accept', 'text/plain') + .expect(200, ' - Tobi\n - Loki\n - Jane\n', done); + }); - it('should accept to application/json', function(done){ + it('should accept to application/json', function (done) { request(app) - .get('/') - .set('Accept', 'application/json') - .expect(200, '[{"name":"Tobi"},{"name":"Loki"},{"name":"Jane"}]', done) - }) - }) + .get('/') + .set('Accept', 'application/json') + .expect(200, '[{"name":"Tobi"},{"name":"Loki"},{"name":"Jane"}]', done); + }); + }); - describe('GET /users', function(){ - it('should default to text/html', function(done){ + describe('GET /users', function () { + it('should default to text/html', function (done) { request(app) - .get('/users') - .expect(200, '', done) - }) + .get('/users') + .expect(200, '', done); + }); - it('should accept to text/plain', function(done){ + it('should accept to text/plain', function (done) { request(app) - .get('/users') - .set('Accept', 'text/plain') - .expect(200, ' - Tobi\n - Loki\n - Jane\n', done) - }) + .get('/users') + .set('Accept', 'text/plain') + .expect(200, ' - Tobi\n - Loki\n - Jane\n', done); + }); - it('should accept to application/json', function(done){ + it('should accept to application/json', function (done) { request(app) - .get('/users') - .set('Accept', 'application/json') - .expect(200, '[{"name":"Tobi"},{"name":"Loki"},{"name":"Jane"}]', done) - }) - }) -}) + .get('/users') + .set('Accept', 'application/json') + .expect(200, '[{"name":"Tobi"},{"name":"Loki"},{"name":"Jane"}]', done); + }); + }); +}); diff --git a/test/acceptance/cookie-sessions.js b/test/acceptance/cookie-sessions.js index e83c8e419da..3fbb4aa9983 100644 --- a/test/acceptance/cookie-sessions.js +++ b/test/acceptance/cookie-sessions.js @@ -1,38 +1,37 @@ - -var app = require('../../examples/cookie-sessions') -var request = require('supertest') +var app = require('../../examples/cookie-sessions'); +var request = require('supertest'); describe('cookie-sessions', function () { describe('GET /', function () { it('should display no views', function (done) { - request(app) - .get('/') - .expect(200, 'viewed 1 times\n', done) - }) + request(app).get('/').expect(200, 'viewed 1 times\n', done); + }); it('should set a session cookie', function (done) { request(app) - .get('/') - .expect('Set-Cookie', /session=/) - .expect(200, done) - }) + .get('/') + .expect('Set-Cookie', /session=/) + .expect(200, done); + }); it('should display 1 view on revisit', function (done) { request(app) - .get('/') - .expect(200, 'viewed 1 times\n', function (err, res) { - if (err) return done(err) - request(app) .get('/') - .set('Cookie', getCookies(res)) - .expect(200, 'viewed 2 times\n', done) - }) - }) - }) -}) + .expect(200, 'viewed 1 times\n', function (err, res) { + if (err) return done(err); + request(app) + .get('/') + .set('Cookie', getCookies(res)) + .expect(200, 'viewed 2 times\n', done); + }); + }); + }); +}); function getCookies(res) { - return res.headers['set-cookie'].map(function (val) { - return val.split(';')[0] - }).join('; '); + return res.headers['set-cookie'] + .map(function (val) { + return val.split(';')[0]; + }) + .join('; '); } diff --git a/test/acceptance/cookies.js b/test/acceptance/cookies.js index aa9e1faef44..b397519f20e 100644 --- a/test/acceptance/cookies.js +++ b/test/acceptance/cookies.js @@ -1,71 +1,68 @@ - -var app = require('../../examples/cookies') - , request = require('supertest'); +var app = require('../../examples/cookies'), + request = require('supertest'); var utils = require('../support/utils'); -describe('cookies', function(){ - describe('GET /', function(){ - it('should have a form', function(done){ - request(app) - .get('/') - .expect(/tobi <tobi@learnboost\.com><\/li>/) - .expect(/
  • loki <loki@learnboost\.com><\/li>/) - .expect(/
  • jane <jane@learnboost\.com><\/li>/) - .expect(200, done) - }) - }) -}) + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect(/
  • tobi <tobi@learnboost\.com><\/li>/) + .expect(/
  • loki <loki@learnboost\.com><\/li>/) + .expect(/
  • jane <jane@learnboost\.com><\/li>/) + .expect(200, done); + }); + }); +}); diff --git a/test/acceptance/error-pages.js b/test/acceptance/error-pages.js index 48feb3fb466..c3aefdb15f6 100644 --- a/test/acceptance/error-pages.js +++ b/test/acceptance/error-pages.js @@ -1,99 +1,85 @@ +var app = require('../../examples/error-pages'), + request = require('supertest'); -var app = require('../../examples/error-pages') - , request = require('supertest'); - -describe('error-pages', function(){ - describe('GET /', function(){ - it('should respond with page list', function(done){ +describe('error-pages', function () { + describe('GET /', function () { + it('should respond with page list', function (done) { request(app) - .get('/') - .expect(/Pages Example/, done) - }) - }) + .get('/') + .expect(/Pages Example/, done); + }); + }); - describe('Accept: text/html',function(){ - describe('GET /403', function(){ - it('should respond with 403', function(done){ - request(app) - .get('/403') - .expect(403, done) - }) - }) + describe('Accept: text/html', function () { + describe('GET /403', function () { + it('should respond with 403', function (done) { + request(app).get('/403').expect(403, done); + }); + }); - describe('GET /404', function(){ - it('should respond with 404', function(done){ - request(app) - .get('/404') - .expect(404, done) - }) - }) + describe('GET /404', function () { + it('should respond with 404', function (done) { + request(app).get('/404').expect(404, done); + }); + }); - describe('GET /500', function(){ - it('should respond with 500', function(done){ - request(app) - .get('/500') - .expect(500, done) - }) - }) - }) + describe('GET /500', function () { + it('should respond with 500', function (done) { + request(app).get('/500').expect(500, done); + }); + }); + }); - describe('Accept: application/json',function(){ - describe('GET /403', function(){ - it('should respond with 403', function(done){ + describe('Accept: application/json', function () { + describe('GET /403', function () { + it('should respond with 403', function (done) { request(app) - .get('/403') - .set('Accept','application/json') - .expect(403, done) - }) - }) + .get('/403') + .set('Accept', 'application/json') + .expect(403, done); + }); + }); - describe('GET /404', function(){ - it('should respond with 404', function(done){ + describe('GET /404', function () { + it('should respond with 404', function (done) { request(app) - .get('/404') - .set('Accept','application/json') - .expect(404, { error: 'Not found' }, done) - }) - }) + .get('/404') + .set('Accept', 'application/json') + .expect(404, { error: 'Not found' }, done); + }); + }); - describe('GET /500', function(){ - it('should respond with 500', function(done){ + describe('GET /500', function () { + it('should respond with 500', function (done) { request(app) - .get('/500') - .set('Accept', 'application/json') - .expect(500, done) - }) - }) - }) + .get('/500') + .set('Accept', 'application/json') + .expect(500, done); + }); + }); + }); + describe('Accept: text/plain', function () { + describe('GET /403', function () { + it('should respond with 403', function (done) { + request(app).get('/403').set('Accept', 'text/plain').expect(403, done); + }); + }); - describe('Accept: text/plain',function(){ - describe('GET /403', function(){ - it('should respond with 403', function(done){ + describe('GET /404', function () { + it('should respond with 404', function (done) { request(app) - .get('/403') - .set('Accept','text/plain') - .expect(403, done) - }) - }) + .get('/404') + .set('Accept', 'text/plain') + .expect(404) + .expect('Not found', done); + }); + }); - describe('GET /404', function(){ - it('should respond with 404', function(done){ - request(app) - .get('/404') - .set('Accept', 'text/plain') - .expect(404) - .expect('Not found', done); - }) - }) - - describe('GET /500', function(){ - it('should respond with 500', function(done){ - request(app) - .get('/500') - .set('Accept','text/plain') - .expect(500, done) - }) - }) - }) -}) + describe('GET /500', function () { + it('should respond with 500', function (done) { + request(app).get('/500').set('Accept', 'text/plain').expect(500, done); + }); + }); + }); +}); diff --git a/test/acceptance/error.js b/test/acceptance/error.js index 6bdf099feed..80fc6d1d948 100644 --- a/test/acceptance/error.js +++ b/test/acceptance/error.js @@ -1,29 +1,22 @@ +var app = require('../../examples/error'), + request = require('supertest'); -var app = require('../../examples/error') - , request = require('supertest'); +describe('error', function () { + describe('GET /', function () { + it('should respond with 500', function (done) { + request(app).get('/').expect(500, done); + }); + }); -describe('error', function(){ - describe('GET /', function(){ - it('should respond with 500', function(done){ - request(app) - .get('/') - .expect(500,done) - }) - }) + describe('GET /next', function () { + it('should respond with 500', function (done) { + request(app).get('/next').expect(500, done); + }); + }); - describe('GET /next', function(){ - it('should respond with 500', function(done){ - request(app) - .get('/next') - .expect(500,done) - }) - }) - - describe('GET /missing', function(){ - it('should respond with 404', function(done){ - request(app) - .get('/missing') - .expect(404,done) - }) - }) -}) + describe('GET /missing', function () { + it('should respond with 404', function (done) { + request(app).get('/missing').expect(404, done); + }); + }); +}); diff --git a/test/acceptance/hello-world.js b/test/acceptance/hello-world.js index db90349c496..fe3c1ebc292 100644 --- a/test/acceptance/hello-world.js +++ b/test/acceptance/hello-world.js @@ -1,21 +1,16 @@ - -var app = require('../../examples/hello-world') -var request = require('supertest') +var app = require('../../examples/hello-world'); +var request = require('supertest'); describe('hello-world', function () { describe('GET /', function () { it('should respond with hello world', function (done) { - request(app) - .get('/') - .expect(200, 'Hello World', done) - }) - }) + request(app).get('/').expect(200, 'Hello World', done); + }); + }); describe('GET /missing', function () { it('should respond with 404', function (done) { - request(app) - .get('/missing') - .expect(404, done) - }) - }) -}) + request(app).get('/missing').expect(404, done); + }); + }); +}); diff --git a/test/acceptance/markdown.js b/test/acceptance/markdown.js index 1a7d9e3cb75..5a2b84cf442 100644 --- a/test/acceptance/markdown.js +++ b/test/acceptance/markdown.js @@ -1,21 +1,18 @@ +var app = require('../../examples/markdown'); +var request = require('supertest'); -var app = require('../../examples/markdown') -var request = require('supertest') - -describe('markdown', function(){ - describe('GET /', function(){ - it('should respond with html', function(done){ +describe('markdown', function () { + describe('GET /', function () { + it('should respond with html', function (done) { request(app) .get('/') - .expect(/]*>Markdown Example<\/h1>/,done) - }) - }) + .expect(/]*>Markdown Example<\/h1>/, done); + }); + }); - describe('GET /fail',function(){ - it('should respond with an error', function(done){ - request(app) - .get('/fail') - .expect(500,done) - }) - }) -}) + describe('GET /fail', function () { + it('should respond with an error', function (done) { + request(app).get('/fail').expect(500, done); + }); + }); +}); diff --git a/test/acceptance/multi-router.js b/test/acceptance/multi-router.js index 4362a8300be..09f53cf95c8 100644 --- a/test/acceptance/multi-router.js +++ b/test/acceptance/multi-router.js @@ -1,44 +1,42 @@ -var app = require('../../examples/multi-router') -var request = require('supertest') +var app = require('../../examples/multi-router'); +var request = require('supertest'); -describe('multi-router', function(){ - describe('GET /',function(){ - it('should respond with root handler', function(done){ - request(app) - .get('/') - .expect(200, 'Hello from root route.', done) - }) - }) +describe('multi-router', function () { + describe('GET /', function () { + it('should respond with root handler', function (done) { + request(app).get('/').expect(200, 'Hello from root route.', done); + }); + }); - describe('GET /api/v1/',function(){ - it('should respond with APIv1 root handler', function(done){ + describe('GET /api/v1/', function () { + it('should respond with APIv1 root handler', function (done) { request(app) - .get('/api/v1/') - .expect(200, 'Hello from APIv1 root route.', done) - }) - }) + .get('/api/v1/') + .expect(200, 'Hello from APIv1 root route.', done); + }); + }); - describe('GET /api/v1/users',function(){ - it('should respond with users from APIv1', function(done){ + describe('GET /api/v1/users', function () { + it('should respond with users from APIv1', function (done) { request(app) - .get('/api/v1/users') - .expect(200, 'List of APIv1 users.', done) - }) - }) + .get('/api/v1/users') + .expect(200, 'List of APIv1 users.', done); + }); + }); - describe('GET /api/v2/',function(){ - it('should respond with APIv2 root handler', function(done){ + describe('GET /api/v2/', function () { + it('should respond with APIv2 root handler', function (done) { request(app) - .get('/api/v2/') - .expect(200, 'Hello from APIv2 root route.', done) - }) - }) + .get('/api/v2/') + .expect(200, 'Hello from APIv2 root route.', done); + }); + }); - describe('GET /api/v2/users',function(){ - it('should respond with users from APIv2', function(done){ + describe('GET /api/v2/users', function () { + it('should respond with users from APIv2', function (done) { request(app) - .get('/api/v2/users') - .expect(200, 'List of APIv2 users.', done) - }) - }) -}) + .get('/api/v2/users') + .expect(200, 'List of APIv2 users.', done); + }); + }); +}); diff --git a/test/acceptance/mvc.js b/test/acceptance/mvc.js index 35709f6fb46..a6fdff49273 100644 --- a/test/acceptance/mvc.js +++ b/test/acceptance/mvc.js @@ -1,132 +1,114 @@ +var request = require('supertest'), + app = require('../../examples/mvc'); -var request = require('supertest') - , app = require('../../examples/mvc'); +describe('mvc', function () { + describe('GET /', function () { + it('should redirect to /users', function (done) { + request(app).get('/').expect('Location', '/users').expect(302, done); + }); + }); -describe('mvc', function(){ - describe('GET /', function(){ - it('should redirect to /users', function(done){ - request(app) - .get('/') - .expect('Location', '/users') - .expect(302, done) - }) - }) - - describe('GET /pet/0', function(){ - it('should get pet', function(done){ - request(app) - .get('/pet/0') - .expect(200, /Tobi/, done) - }) - }) + describe('GET /pet/0', function () { + it('should get pet', function (done) { + request(app).get('/pet/0').expect(200, /Tobi/, done); + }); + }); - describe('GET /pet/0/edit', function(){ - it('should get pet edit page', function(done){ - request(app) - .get('/pet/0/edit') - .expect(/Users<\/h1>/) - .expect(/>TJGuillermoNathanUsers<\/h1>/) + .expect(/>TJGuillermoNathanTJ edit/, done) - }) + .get('/user/0') + .expect(200, /

    TJ edit/, done); + }); - it('should display the users pets', function(done){ + it('should display the users pets', function (done) { request(app) - .get('/user/0') - .expect(/\/pet\/0">Tobi/) - .expect(/\/pet\/1">Loki/) - .expect(/\/pet\/2">Jane/) - .expect(200, done) - }) - }) + .get('/user/0') + .expect(/\/pet\/0">Tobi/) + .expect(/\/pet\/1">Loki/) + .expect(/\/pet\/2">Jane/) + .expect(200, done); + }); + }); - describe('when not present', function(){ - it('should 404', function(done){ - request(app) - .get('/user/123') - .expect(404, done); - }) - }) - }) + describe('when not present', function () { + it('should 404', function (done) { + request(app).get('/user/123').expect(404, done); + }); + }); + }); - describe('GET /user/:id/edit', function(){ - it('should display the edit form', function(done){ + describe('GET /user/:id/edit', function () { + it('should display the edit form', function (done) { request(app) - .get('/user/1/edit') - .expect(/Guillermo/) - .expect(200, /Examples:<\/h1>/,done) - }) - }) + .expect(/^

    Examples:<\/h1>/, done); + }); + }); - describe('GET /users', function(){ - it('should respond with all users', function(done){ + describe('GET /users', function () { + it('should respond with all users', function (done) { request(app) .get('/users') - .expect(/^\[{"name":"tj"},{"name":"ciaran"},{"name":"aaron"},{"name":"guillermo"},{"name":"simon"},{"name":"tobi"}\]/,done) - }) - }) + .expect( + /^\[{"name":"tj"},{"name":"ciaran"},{"name":"aaron"},{"name":"guillermo"},{"name":"simon"},{"name":"tobi"}\]/, + done, + ); + }); + }); - describe('GET /users/1', function(){ - it('should respond with user 1', function(done){ + describe('GET /users/1', function () { + it('should respond with user 1', function (done) { request(app) .get('/users/1') - .expect(/^{"name":"ciaran"}/,done) - }) - }) + .expect(/^{"name":"ciaran"}/, done); + }); + }); - describe('GET /users/9', function(){ - it('should respond with error', function(done){ - request(app) - .get('/users/9') - .expect('{"error":"Cannot find user"}', done) - }) - }) + describe('GET /users/9', function () { + it('should respond with error', function (done) { + request(app).get('/users/9').expect('{"error":"Cannot find user"}', done); + }); + }); - describe('GET /users/1..3', function(){ - it('should respond with users 1 through 3', function(done){ + describe('GET /users/1..3', function () { + it('should respond with users 1 through 3', function (done) { request(app) .get('/users/1..3') - .expect(/^
    • ciaran<\/li>\n
    • aaron<\/li>\n
    • guillermo<\/li><\/ul>/,done) - }) - }) + .expect( + /^
      • ciaran<\/li>\n
      • aaron<\/li>\n
      • guillermo<\/li><\/ul>/, + done, + ); + }); + }); - describe('DELETE /users/1', function(){ - it('should delete user 1', function(done){ + describe('DELETE /users/1', function () { + it('should delete user 1', function (done) { request(app) .del('/users/1') - .expect(/^destroyed/,done) - }) - }) + .expect(/^destroyed/, done); + }); + }); - describe('DELETE /users/9', function(){ - it('should fail', function(done){ - request(app) - .del('/users/9') - .expect('Cannot find user', done) - }) - }) + describe('DELETE /users/9', function () { + it('should fail', function (done) { + request(app).del('/users/9').expect('Cannot find user', done); + }); + }); - describe('GET /users/1..3.json', function(){ - it('should respond with users 2 and 3 as json', function(done){ + describe('GET /users/1..3.json', function () { + it('should respond with users 2 and 3 as json', function (done) { request(app) .get('/users/1..3.json') - .expect(/^\[null,{"name":"aaron"},{"name":"guillermo"}\]/,done) - }) - }) -}) + .expect(/^\[null,{"name":"aaron"},{"name":"guillermo"}\]/, done); + }); + }); +}); diff --git a/test/acceptance/route-map.js b/test/acceptance/route-map.js index 0bd2a6d32e1..17566147c5f 100644 --- a/test/acceptance/route-map.js +++ b/test/acceptance/route-map.js @@ -1,45 +1,34 @@ +var request = require('supertest'), + app = require('../../examples/route-map'); -var request = require('supertest') - , app = require('../../examples/route-map'); +describe('route-map', function () { + describe('GET /users', function () { + it('should respond with users', function (done) { + request(app).get('/users').expect('user list', done); + }); + }); -describe('route-map', function(){ - describe('GET /users', function(){ - it('should respond with users', function(done){ - request(app) - .get('/users') - .expect('user list', done); - }) - }) + describe('DELETE /users', function () { + it('should delete users', function (done) { + request(app).del('/users').expect('delete users', done); + }); + }); - describe('DELETE /users', function(){ - it('should delete users', function(done){ - request(app) - .del('/users') - .expect('delete users', done); - }) - }) + describe('GET /users/:id', function () { + it('should get a user', function (done) { + request(app).get('/users/12').expect('user 12', done); + }); + }); - describe('GET /users/:id', function(){ - it('should get a user', function(done){ - request(app) - .get('/users/12') - .expect('user 12', done); - }) - }) + describe('GET /users/:id/pets', function () { + it('should get a users pets', function (done) { + request(app).get('/users/12/pets').expect("user 12's pets", done); + }); + }); - describe('GET /users/:id/pets', function(){ - it('should get a users pets', function(done){ - request(app) - .get('/users/12/pets') - .expect('user 12\'s pets', done); - }) - }) - - describe('GET /users/:id/pets/:pid', function(){ - it('should get a users pet', function(done){ - request(app) - .del('/users/12/pets/2') - .expect('delete 12\'s pet 2', done); - }) - }) -}) + describe('GET /users/:id/pets/:pid', function () { + it('should get a users pet', function (done) { + request(app).del('/users/12/pets/2').expect("delete 12's pet 2", done); + }); + }); +}); diff --git a/test/acceptance/route-separation.js b/test/acceptance/route-separation.js index 867fd295271..527ac95e43c 100644 --- a/test/acceptance/route-separation.js +++ b/test/acceptance/route-separation.js @@ -1,97 +1,86 @@ - -var app = require('../../examples/route-separation') -var request = require('supertest') +var app = require('../../examples/route-separation'); +var request = require('supertest'); describe('route-separation', function () { describe('GET /', function () { it('should respond with index', function (done) { request(app) - .get('/') - .expect(200, /Route Separation Example/, done) - }) - }) + .get('/') + .expect(200, /Route Separation Example/, done); + }); + }); describe('GET /users', function () { it('should list users', function (done) { - request(app) - .get('/users') - .expect(/TJ/) - .expect(/Tobi/) - .expect(200, done) - }) - }) + request(app).get('/users').expect(/TJ/).expect(/Tobi/).expect(200, done); + }); + }); describe('GET /user/:id', function () { it('should get a user', function (done) { request(app) - .get('/user/0') - .expect(200, /Viewing user TJ/, done) - }) + .get('/user/0') + .expect(200, /Viewing user TJ/, done); + }); it('should 404 on missing user', function (done) { - request(app) - .get('/user/10') - .expect(404, done) - }) - }) + request(app).get('/user/10').expect(404, done); + }); + }); describe('GET /user/:id/view', function () { it('should get a user', function (done) { request(app) - .get('/user/0/view') - .expect(200, /Viewing user TJ/, done) - }) + .get('/user/0/view') + .expect(200, /Viewing user TJ/, done); + }); it('should 404 on missing user', function (done) { - request(app) - .get('/user/10/view') - .expect(404, done) - }) - }) + request(app).get('/user/10/view').expect(404, done); + }); + }); describe('GET /user/:id/edit', function () { it('should get a user to edit', function (done) { request(app) - .get('/user/0/edit') - .expect(200, /Editing user TJ/, done) - }) - }) + .get('/user/0/edit') + .expect(200, /Editing user TJ/, done); + }); + }); describe('PUT /user/:id/edit', function () { it('should edit a user', function (done) { request(app) - .put('/user/0/edit') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send({ user: { name: 'TJ', email: 'tj-invalid@vision-media.ca' } }) - .expect(302, function (err) { - if (err) return done(err) - request(app) - .get('/user/0') - .expect(200, /tj-invalid@vision-media\.ca/, done) - }) - }) - }) + .put('/user/0/edit') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send({ user: { name: 'TJ', email: 'tj-invalid@vision-media.ca' } }) + .expect(302, function (err) { + if (err) return done(err); + request(app) + .get('/user/0') + .expect(200, /tj-invalid@vision-media\.ca/, done); + }); + }); + }); describe('POST /user/:id/edit?_method=PUT', function () { it('should edit a user', function (done) { request(app) - .post('/user/1/edit?_method=PUT') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send({ user: { name: 'Tobi', email: 'tobi-invalid@vision-media.ca' } }) - .expect(302, function (err) { - if (err) return done(err) - request(app) - .get('/user/1') - .expect(200, /tobi-invalid@vision-media\.ca/, done) - }) - }) - }) + .post('/user/1/edit?_method=PUT') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send({ user: { name: 'Tobi', email: 'tobi-invalid@vision-media.ca' } }) + .expect(302, function (err) { + if (err) return done(err); + request(app) + .get('/user/1') + .expect(200, /tobi-invalid@vision-media\.ca/, done); + }); + }); + }); describe('GET /posts', function () { it('should get a list of posts', function (done) { - request(app) - .get('/posts') - .expect(200, /Posts/, done) - }) - }) -}) + request(app).get('/posts').expect(200, /Posts/, done); + }); + }); +}); diff --git a/test/acceptance/vhost.js b/test/acceptance/vhost.js index 1b633d4b2bc..76a46fe3cf2 100644 --- a/test/acceptance/vhost.js +++ b/test/acceptance/vhost.js @@ -1,46 +1,46 @@ -var app = require('../../examples/vhost') -var request = require('supertest') +var app = require('../../examples/vhost'); +var request = require('supertest'); -describe('vhost', function(){ - describe('example.com', function(){ - describe('GET /', function(){ - it('should say hello', function(done){ +describe('vhost', function () { + describe('example.com', function () { + describe('GET /', function () { + it('should say hello', function (done) { request(app) - .get('/') - .set('Host', 'example.com') - .expect(200, /hello/i, done) - }) - }) + .get('/') + .set('Host', 'example.com') + .expect(200, /hello/i, done); + }); + }); - describe('GET /foo', function(){ - it('should say foo', function(done){ + describe('GET /foo', function () { + it('should say foo', function (done) { request(app) - .get('/foo') - .set('Host', 'example.com') - .expect(200, 'requested foo', done) - }) - }) - }) + .get('/foo') + .set('Host', 'example.com') + .expect(200, 'requested foo', done); + }); + }); + }); - describe('foo.example.com', function(){ - describe('GET /', function(){ - it('should redirect to /foo', function(done){ + describe('foo.example.com', function () { + describe('GET /', function () { + it('should redirect to /foo', function (done) { request(app) - .get('/') - .set('Host', 'foo.example.com') - .expect(302, /Redirecting to http:\/\/example.com:3000\/foo/, done) - }) - }) - }) + .get('/') + .set('Host', 'foo.example.com') + .expect(302, /Redirecting to http:\/\/example.com:3000\/foo/, done); + }); + }); + }); - describe('bar.example.com', function(){ - describe('GET /', function(){ - it('should redirect to /bar', function(done){ + describe('bar.example.com', function () { + describe('GET /', function () { + it('should redirect to /bar', function (done) { request(app) - .get('/') - .set('Host', 'bar.example.com') - .expect(302, /Redirecting to http:\/\/example.com:3000\/bar/, done) - }) - }) - }) -}) + .get('/') + .set('Host', 'bar.example.com') + .expect(302, /Redirecting to http:\/\/example.com:3000\/bar/, done); + }); + }); + }); +}); diff --git a/test/acceptance/web-service.js b/test/acceptance/web-service.js index 2e37b48c8ca..988fea9da82 100644 --- a/test/acceptance/web-service.js +++ b/test/acceptance/web-service.js @@ -1,105 +1,94 @@ +var request = require('supertest'), + app = require('../../examples/web-service'); -var request = require('supertest') - , app = require('../../examples/web-service'); +describe('web-service', function () { + describe('GET /api/users', function () { + describe('without an api key', function () { + it('should respond with 400 bad request', function (done) { + request(app).get('/api/users').expect(400, done); + }); + }); -describe('web-service', function(){ - describe('GET /api/users', function(){ - describe('without an api key', function(){ - it('should respond with 400 bad request', function(done){ - request(app) - .get('/api/users') - .expect(400, done); - }) - }) - - describe('with an invalid api key', function(){ - it('should respond with 401 unauthorized', function(done){ - request(app) - .get('/api/users?api-key=rawr') - .expect(401, done); - }) - }) + describe('with an invalid api key', function () { + it('should respond with 401 unauthorized', function (done) { + request(app).get('/api/users?api-key=rawr').expect(401, done); + }); + }); - describe('with a valid api key', function(){ - it('should respond users json', function(done){ + describe('with a valid api key', function () { + it('should respond users json', function (done) { request(app) - .get('/api/users?api-key=foo') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '[{"name":"tobi"},{"name":"loki"},{"name":"jane"}]', done) - }) - }) - }) + .get('/api/users?api-key=foo') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect( + 200, + '[{"name":"tobi"},{"name":"loki"},{"name":"jane"}]', + done, + ); + }); + }); + }); - describe('GET /api/repos', function(){ - describe('without an api key', function(){ - it('should respond with 400 bad request', function(done){ - request(app) - .get('/api/repos') - .expect(400, done); - }) - }) + describe('GET /api/repos', function () { + describe('without an api key', function () { + it('should respond with 400 bad request', function (done) { + request(app).get('/api/repos').expect(400, done); + }); + }); - describe('with an invalid api key', function(){ - it('should respond with 401 unauthorized', function(done){ - request(app) - .get('/api/repos?api-key=rawr') - .expect(401, done); - }) - }) + describe('with an invalid api key', function () { + it('should respond with 401 unauthorized', function (done) { + request(app).get('/api/repos?api-key=rawr').expect(401, done); + }); + }); - describe('with a valid api key', function(){ - it('should respond repos json', function(done){ + describe('with a valid api key', function () { + it('should respond repos json', function (done) { request(app) - .get('/api/repos?api-key=foo') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(/"name":"express"/) - .expect(/"url":"https:\/\/github.com\/expressjs\/express"/) - .expect(200, done) - }) - }) - }) + .get('/api/repos?api-key=foo') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(/"name":"express"/) + .expect(/"url":"https:\/\/github.com\/expressjs\/express"/) + .expect(200, done); + }); + }); + }); - describe('GET /api/user/:name/repos', function(){ - describe('without an api key', function(){ - it('should respond with 400 bad request', function(done){ - request(app) - .get('/api/user/loki/repos') - .expect(400, done); - }) - }) + describe('GET /api/user/:name/repos', function () { + describe('without an api key', function () { + it('should respond with 400 bad request', function (done) { + request(app).get('/api/user/loki/repos').expect(400, done); + }); + }); - describe('with an invalid api key', function(){ - it('should respond with 401 unauthorized', function(done){ - request(app) - .get('/api/user/loki/repos?api-key=rawr') - .expect(401, done); - }) - }) + describe('with an invalid api key', function () { + it('should respond with 401 unauthorized', function (done) { + request(app).get('/api/user/loki/repos?api-key=rawr').expect(401, done); + }); + }); - describe('with a valid api key', function(){ - it('should respond user repos json', function(done){ + describe('with a valid api key', function () { + it('should respond user repos json', function (done) { request(app) - .get('/api/user/loki/repos?api-key=foo') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(/"name":"stylus"/) - .expect(/"url":"https:\/\/github.com\/learnboost\/stylus"/) - .expect(200, done) - }) + .get('/api/user/loki/repos?api-key=foo') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(/"name":"stylus"/) + .expect(/"url":"https:\/\/github.com\/learnboost\/stylus"/) + .expect(200, done); + }); - it('should 404 with unknown user', function(done){ - request(app) - .get('/api/user/bob/repos?api-key=foo') - .expect(404, done) - }) - }) - }) + it('should 404 with unknown user', function (done) { + request(app).get('/api/user/bob/repos?api-key=foo').expect(404, done); + }); + }); + }); - describe('when requesting an invalid route', function(){ - it('should respond with 404 json', function(done){ + describe('when requesting an invalid route', function () { + it('should respond with 404 json', function (done) { request(app) .get('/api/something?api-key=bar') .expect('Content-Type', /json/) - .expect(404, '{"error":"Sorry, can\'t find that"}', done) - }) - }) -}) + .expect(404, '{"error":"Sorry, can\'t find that"}', done); + }); + }); +}); diff --git a/test/app.all.js b/test/app.all.js index e4afca7d731..db877229222 100644 --- a/test/app.all.js +++ b/test/app.all.js @@ -1,38 +1,32 @@ -'use strict' +'use strict'; -var after = require('after') -var express = require('../') - , request = require('supertest'); +var after = require('after'); +var express = require('../'), + request = require('supertest'); -describe('app.all()', function(){ - it('should add a router per method', function(done){ +describe('app.all()', function () { + it('should add a router per method', function (done) { var app = express(); - var cb = after(2, done) + var cb = after(2, done); - app.all('/tobi', function(req, res){ + app.all('/tobi', function (req, res) { res.end(req.method); }); - request(app) - .put('/tobi') - .expect(200, 'PUT', cb) + request(app).put('/tobi').expect(200, 'PUT', cb); - request(app) - .get('/tobi') - .expect(200, 'GET', cb) - }) + request(app).get('/tobi').expect(200, 'GET', cb); + }); - it('should run the callback for a method just once', function(done){ - var app = express() - , n = 0; + it('should run the callback for a method just once', function (done) { + var app = express(), + n = 0; - app.all('/*splat', function(req, res, next){ + app.all('/*splat', function (req, res, next) { if (n++) return done(new Error('DELETE called several times')); next(); }); - request(app) - .del('/tobi') - .expect(404, done); - }) -}) + request(app).del('/tobi').expect(404, done); + }); +}); diff --git a/test/app.engine.js b/test/app.engine.js index 214510a94c0..77cb2428a66 100644 --- a/test/app.engine.js +++ b/test/app.engine.js @@ -1,83 +1,83 @@ -'use strict' +'use strict'; -var assert = require('assert') -var express = require('../') - , fs = require('fs'); -var path = require('path') +var assert = require('assert'); +var express = require('../'), + fs = require('fs'); +var path = require('path'); function render(path, options, fn) { - fs.readFile(path, 'utf8', function(err, str){ + fs.readFile(path, 'utf8', function (err, str) { if (err) return fn(err); str = str.replace('{{user.name}}', options.user.name); fn(null, str); }); } -describe('app', function(){ - describe('.engine(ext, fn)', function(){ - it('should map a template engine', function(done){ +describe('app', function () { + describe('.engine(ext, fn)', function () { + it('should map a template engine', function (done) { var app = express(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.engine('.html', render); app.locals.user = { name: 'tobi' }; - app.render('user.html', function(err, str){ + app.render('user.html', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) + }); + }); - it('should throw when the callback is missing', function(){ + it('should throw when the callback is missing', function () { var app = express(); assert.throws(function () { app.engine('.html', null); - }, /callback function required/) - }) + }, /callback function required/); + }); - it('should work without leading "."', function(done){ + it('should work without leading "."', function (done) { var app = express(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.engine('html', render); app.locals.user = { name: 'tobi' }; - app.render('user.html', function(err, str){ + app.render('user.html', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) + }); + }); - it('should work "view engine" setting', function(done){ + it('should work "view engine" setting', function (done) { var app = express(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.engine('html', render); app.set('view engine', 'html'); app.locals.user = { name: 'tobi' }; - app.render('user', function(err, str){ + app.render('user', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) + }); + }); - it('should work "view engine" with leading "."', function(done){ + it('should work "view engine" with leading "."', function (done) { var app = express(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.engine('.html', render); app.set('view engine', '.html'); app.locals.user = { name: 'tobi' }; - app.render('user', function(err, str){ + app.render('user', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) - }) -}) + }); + }); + }); +}); diff --git a/test/app.head.js b/test/app.head.js index fabb98795ab..757e78bca19 100644 --- a/test/app.head.js +++ b/test/app.head.js @@ -1,66 +1,61 @@ -'use strict' +'use strict'; var express = require('../'); var request = require('supertest'); var assert = require('assert'); -describe('HEAD', function(){ - it('should default to GET', function(done){ +describe('HEAD', function () { + it('should default to GET', function (done) { var app = express(); - app.get('/tobi', function(req, res){ + app.get('/tobi', function (req, res) { // send() detects HEAD res.send('tobi'); }); - request(app) - .head('/tobi') - .expect(200, done); - }) + request(app).head('/tobi').expect(200, done); + }); - it('should output the same headers as GET requests', function(done){ + it('should output the same headers as GET requests', function (done) { var app = express(); - app.get('/tobi', function(req, res){ + app.get('/tobi', function (req, res) { // send() detects HEAD res.send('tobi'); }); request(app) - .head('/tobi') - .expect(200, function(err, res){ - if (err) return done(err); - var headers = res.headers; - request(app) - .get('/tobi') - .expect(200, function(err, res){ + .head('/tobi') + .expect(200, function (err, res) { if (err) return done(err); - delete headers.date; - delete res.headers.date; - assert.deepEqual(res.headers, headers); - done(); + var headers = res.headers; + request(app) + .get('/tobi') + .expect(200, function (err, res) { + if (err) return done(err); + delete headers.date; + delete res.headers.date; + assert.deepEqual(res.headers, headers); + done(); + }); }); - }); - }) -}) + }); +}); -describe('app.head()', function(){ - it('should override', function(done){ - var app = express() +describe('app.head()', function () { + it('should override', function (done) { + var app = express(); - app.head('/tobi', function(req, res){ - res.header('x-method', 'head') - res.end() + app.head('/tobi', function (req, res) { + res.header('x-method', 'head'); + res.end(); }); - app.get('/tobi', function(req, res){ - res.header('x-method', 'get') + app.get('/tobi', function (req, res) { + res.header('x-method', 'get'); res.send('tobi'); }); - request(app) - .head('/tobi') - .expect('x-method', 'head') - .expect(200, done) - }) -}) + request(app).head('/tobi').expect('x-method', 'head').expect(200, done); + }); +}); diff --git a/test/app.js b/test/app.js index fe7d4c2758a..280a5789282 100644 --- a/test/app.js +++ b/test/app.js @@ -1,45 +1,43 @@ -'use strict' +'use strict'; -var assert = require('assert') -var express = require('..') -var request = require('supertest') +var assert = require('assert'); +var express = require('..'); +var request = require('supertest'); -describe('app', function(){ - it('should inherit from event emitter', function(done){ +describe('app', function () { + it('should inherit from event emitter', function (done) { var app = express(); app.on('foo', done); app.emit('foo'); - }) + }); - it('should be callable', function(){ + it('should be callable', function () { var app = express(); assert.equal(typeof app, 'function'); - }) + }); - it('should 404 without routes', function(done){ - request(express()) - .get('/') - .expect(404, done); - }) -}) + it('should 404 without routes', function (done) { + request(express()).get('/').expect(404, done); + }); +}); -describe('app.parent', function(){ - it('should return the parent when mounted', function(){ - var app = express() - , blog = express() - , blogAdmin = express(); +describe('app.parent', function () { + it('should return the parent when mounted', function () { + var app = express(), + blog = express(), + blogAdmin = express(); app.use('/blog', blog); blog.use('/admin', blogAdmin); assert(!app.parent, 'app.parent'); - assert.strictEqual(blog.parent, app) - assert.strictEqual(blogAdmin.parent, blog) - }) -}) + assert.strictEqual(blog.parent, app); + assert.strictEqual(blogAdmin.parent, blog); + }); +}); -describe('app.mountpath', function(){ - it('should return the mounted path', function(){ +describe('app.mountpath', function () { + it('should return the mounted path', function () { var admin = express(); var app = express(); var blog = express(); @@ -49,72 +47,72 @@ describe('app.mountpath', function(){ app.use(fallback); blog.use('/admin', admin); - assert.strictEqual(admin.mountpath, '/admin') - assert.strictEqual(app.mountpath, '/') - assert.strictEqual(blog.mountpath, '/blog') - assert.strictEqual(fallback.mountpath, '/') - }) -}) + assert.strictEqual(admin.mountpath, '/admin'); + assert.strictEqual(app.mountpath, '/'); + assert.strictEqual(blog.mountpath, '/blog'); + assert.strictEqual(fallback.mountpath, '/'); + }); +}); -describe('app.path()', function(){ - it('should return the canonical', function(){ - var app = express() - , blog = express() - , blogAdmin = express(); +describe('app.path()', function () { + it('should return the canonical', function () { + var app = express(), + blog = express(), + blogAdmin = express(); app.use('/blog', blog); blog.use('/admin', blogAdmin); - assert.strictEqual(app.path(), '') - assert.strictEqual(blog.path(), '/blog') - assert.strictEqual(blogAdmin.path(), '/blog/admin') - }) -}) + assert.strictEqual(app.path(), ''); + assert.strictEqual(blog.path(), '/blog'); + assert.strictEqual(blogAdmin.path(), '/blog/admin'); + }); +}); -describe('in development', function(){ +describe('in development', function () { before(function () { - this.env = process.env.NODE_ENV - process.env.NODE_ENV = 'development' - }) + this.env = process.env.NODE_ENV; + process.env.NODE_ENV = 'development'; + }); after(function () { - process.env.NODE_ENV = this.env - }) + process.env.NODE_ENV = this.env; + }); - it('should disable "view cache"', function(){ + it('should disable "view cache"', function () { var app = express(); - assert.ok(!app.enabled('view cache')) - }) -}) + assert.ok(!app.enabled('view cache')); + }); +}); -describe('in production', function(){ +describe('in production', function () { before(function () { - this.env = process.env.NODE_ENV - process.env.NODE_ENV = 'production' - }) + this.env = process.env.NODE_ENV; + process.env.NODE_ENV = 'production'; + }); after(function () { - process.env.NODE_ENV = this.env - }) + process.env.NODE_ENV = this.env; + }); - it('should enable "view cache"', function(){ + it('should enable "view cache"', function () { var app = express(); - assert.ok(app.enabled('view cache')) - }) -}) + assert.ok(app.enabled('view cache')); + }); +}); -describe('without NODE_ENV', function(){ +describe('without NODE_ENV', function () { before(function () { - this.env = process.env.NODE_ENV - process.env.NODE_ENV = '' - }) + this.env = process.env.NODE_ENV; + process.env.NODE_ENV = ''; + }); after(function () { - process.env.NODE_ENV = this.env - }) + process.env.NODE_ENV = this.env; + }); - it('should default to development', function(){ + it('should default to development', function () { var app = express(); - assert.strictEqual(app.get('env'), 'development') - }) -}) + assert.strictEqual(app.get('env'), 'development'); + }); +}); diff --git a/test/app.listen.js b/test/app.listen.js index 7e7e731a3b8..e7d228b2180 100644 --- a/test/app.listen.js +++ b/test/app.listen.js @@ -1,27 +1,27 @@ -'use strict' +'use strict'; -var express = require('../') -var assert = require('assert') +var express = require('../'); +var assert = require('assert'); -describe('app.listen()', function(){ - it('should wrap with an HTTP server', function(done){ +describe('app.listen()', function () { + it('should wrap with an HTTP server', function (done) { var app = express(); var server = app.listen(0, function () { - server.close(done) + server.close(done); }); - }) + }); it('should callback on HTTP server errors', function (done) { - var app1 = express() - var app2 = express() + var app1 = express(); + var app2 = express(); var server1 = app1.listen(0, function (err) { - assert(!err) + assert(!err); app2.listen(server1.address().port, function (err) { - assert(err.code === 'EADDRINUSE') - server1.close() - done() - }) - }) - }) -}) + assert(err.code === 'EADDRINUSE'); + server1.close(); + done(); + }); + }); + }); +}); diff --git a/test/app.locals.js b/test/app.locals.js index a4f804fe2a2..7d40786f2d6 100644 --- a/test/app.locals.js +++ b/test/app.locals.js @@ -1,26 +1,26 @@ -'use strict' +'use strict'; -var assert = require('assert') -var express = require('../') +var assert = require('assert'); +var express = require('../'); -describe('app', function(){ +describe('app', function () { describe('.locals', function () { it('should default object with null prototype', function () { - var app = express() - assert.ok(app.locals) - assert.strictEqual(typeof app.locals, 'object') - assert.strictEqual(Object.getPrototypeOf(app.locals), null) - }) + var app = express(); + assert.ok(app.locals); + assert.strictEqual(typeof app.locals, 'object'); + assert.strictEqual(Object.getPrototypeOf(app.locals), null); + }); describe('.settings', function () { it('should contain app settings ', function () { - var app = express() - app.set('title', 'Express') - assert.ok(app.locals.settings) - assert.strictEqual(typeof app.locals.settings, 'object') - assert.strictEqual(app.locals.settings, app.settings) - assert.strictEqual(app.locals.settings.title, 'Express') - }) - }) - }) -}) + var app = express(); + app.set('title', 'Express'); + assert.ok(app.locals.settings); + assert.strictEqual(typeof app.locals.settings, 'object'); + assert.strictEqual(app.locals.settings, app.settings); + assert.strictEqual(app.locals.settings.title, 'Express'); + }); + }); + }); +}); diff --git a/test/app.options.js b/test/app.options.js index ee4c81631cb..72356565fd6 100644 --- a/test/app.options.js +++ b/test/app.options.js @@ -1,84 +1,82 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('OPTIONS', function(){ - it('should default to the routes defined', function(done){ +describe('OPTIONS', function () { + it('should default to the routes defined', function (done) { var app = express(); - app.post('/', function(){}); - app.get('/users', function(req, res){}); - app.put('/users', function(req, res){}); + app.post('/', function () {}); + app.get('/users', function (req, res) {}); + app.put('/users', function (req, res) {}); request(app) - .options('/users') - .expect('Allow', 'GET, HEAD, PUT') - .expect(200, 'GET, HEAD, PUT', done); - }) + .options('/users') + .expect('Allow', 'GET, HEAD, PUT') + .expect(200, 'GET, HEAD, PUT', done); + }); - it('should only include each method once', function(done){ + it('should only include each method once', function (done) { var app = express(); - app.delete('/', function(){}); - app.get('/users', function(req, res){}); - app.put('/users', function(req, res){}); - app.get('/users', function(req, res){}); + app.delete('/', function () {}); + app.get('/users', function (req, res) {}); + app.put('/users', function (req, res) {}); + app.get('/users', function (req, res) {}); request(app) - .options('/users') - .expect('Allow', 'GET, HEAD, PUT') - .expect(200, 'GET, HEAD, PUT', done); - }) + .options('/users') + .expect('Allow', 'GET, HEAD, PUT') + .expect(200, 'GET, HEAD, PUT', done); + }); - it('should not be affected by app.all', function(done){ + it('should not be affected by app.all', function (done) { var app = express(); - app.get('/', function(){}); - app.get('/users', function(req, res){}); - app.put('/users', function(req, res){}); - app.all('/users', function(req, res, next){ + app.get('/', function () {}); + app.get('/users', function (req, res) {}); + app.put('/users', function (req, res) {}); + app.all('/users', function (req, res, next) { res.setHeader('x-hit', '1'); next(); }); request(app) - .options('/users') - .expect('x-hit', '1') - .expect('Allow', 'GET, HEAD, PUT') - .expect(200, 'GET, HEAD, PUT', done); - }) + .options('/users') + .expect('x-hit', '1') + .expect('Allow', 'GET, HEAD, PUT') + .expect(200, 'GET, HEAD, PUT', done); + }); - it('should not respond if the path is not defined', function(done){ + it('should not respond if the path is not defined', function (done) { var app = express(); - app.get('/users', function(req, res){}); + app.get('/users', function (req, res) {}); - request(app) - .options('/other') - .expect(404, done); - }) + request(app).options('/other').expect(404, done); + }); - it('should forward requests down the middleware chain', function(done){ + it('should forward requests down the middleware chain', function (done) { var app = express(); var router = new express.Router(); - router.get('/users', function(req, res){}); + router.get('/users', function (req, res) {}); app.use(router); - app.get('/other', function(req, res){}); + app.get('/other', function (req, res) {}); request(app) - .options('/other') - .expect('Allow', 'GET, HEAD') - .expect(200, 'GET, HEAD', done); - }) + .options('/other') + .expect('Allow', 'GET, HEAD') + .expect(200, 'GET, HEAD', done); + }); describe('when error occurs in response handler', function () { it('should pass error to callback', function (done) { var app = express(); var router = express.Router(); - router.get('/users', function(req, res){}); + router.get('/users', function (req, res) {}); app.use(function (req, res, next) { res.writeHead(200); @@ -89,28 +87,23 @@ describe('OPTIONS', function(){ res.end('true'); }); - request(app) - .options('/users') - .expect(200, 'true', done) - }) - }) -}) + request(app).options('/users').expect(200, 'true', done); + }); + }); +}); -describe('app.options()', function(){ - it('should override the default behavior', function(done){ +describe('app.options()', function () { + it('should override the default behavior', function (done) { var app = express(); - app.options('/users', function(req, res){ + app.options('/users', function (req, res) { res.set('Allow', 'GET'); res.send('GET'); }); - app.get('/users', function(req, res){}); - app.put('/users', function(req, res){}); + app.get('/users', function (req, res) {}); + app.put('/users', function (req, res) {}); - request(app) - .options('/users') - .expect('GET') - .expect('Allow', 'GET', done); - }) -}) + request(app).options('/users').expect('GET').expect('Allow', 'GET', done); + }); +}); diff --git a/test/app.param.js b/test/app.param.js index 5c9a5630870..d84e5edaf31 100644 --- a/test/app.param.js +++ b/test/app.param.js @@ -1,148 +1,138 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('app', function(){ - describe('.param(names, fn)', function(){ - it('should map the array', function(done){ +describe('app', function () { + describe('.param(names, fn)', function () { + it('should map the array', function (done) { var app = express(); - app.param(['id', 'uid'], function(req, res, next, id){ + app.param(['id', 'uid'], function (req, res, next, id) { id = Number(id); if (isNaN(id)) return next('route'); req.params.id = id; next(); }); - app.get('/post/:id', function(req, res){ + app.get('/post/:id', function (req, res) { var id = req.params.id; - res.send((typeof id) + ':' + id) + res.send(typeof id + ':' + id); }); - app.get('/user/:uid', function(req, res){ + app.get('/user/:uid', function (req, res) { var id = req.params.id; - res.send((typeof id) + ':' + id) + res.send(typeof id + ':' + id); }); request(app) .get('/user/123') .expect(200, 'number:123', function (err) { - if (err) return done(err) - request(app) - .get('/post/123') - .expect('number:123', done) - }) - }) - }) - - describe('.param(name, fn)', function(){ - it('should map logic for a single param', function(done){ + if (err) return done(err); + request(app).get('/post/123').expect('number:123', done); + }); + }); + }); + + describe('.param(name, fn)', function () { + it('should map logic for a single param', function (done) { var app = express(); - app.param('id', function(req, res, next, id){ + app.param('id', function (req, res, next, id) { id = Number(id); if (isNaN(id)) return next('route'); req.params.id = id; next(); }); - app.get('/user/:id', function(req, res){ + app.get('/user/:id', function (req, res) { var id = req.params.id; - res.send((typeof id) + ':' + id) + res.send(typeof id + ':' + id); }); - request(app) - .get('/user/123') - .expect(200, 'number:123', done) - }) + request(app).get('/user/123').expect(200, 'number:123', done); + }); - it('should only call once per request', function(done) { + it('should only call once per request', function (done) { var app = express(); var called = 0; var count = 0; - app.param('user', function(req, res, next, user) { + app.param('user', function (req, res, next, user) { called++; req.user = user; next(); }); - app.get('/foo/:user', function(req, res, next) { + app.get('/foo/:user', function (req, res, next) { count++; next(); }); - app.get('/foo/:user', function(req, res, next) { + app.get('/foo/:user', function (req, res, next) { count++; next(); }); - app.use(function(req, res) { + app.use(function (req, res) { res.end([count, called, req.user].join(' ')); }); - request(app) - .get('/foo/bob') - .expect('2 1 bob', done); - }) + request(app).get('/foo/bob').expect('2 1 bob', done); + }); - it('should call when values differ', function(done) { + it('should call when values differ', function (done) { var app = express(); var called = 0; var count = 0; - app.param('user', function(req, res, next, user) { + app.param('user', function (req, res, next, user) { called++; req.users = (req.users || []).concat(user); next(); }); - app.get('/:user/bob', function(req, res, next) { + app.get('/:user/bob', function (req, res, next) { count++; next(); }); - app.get('/foo/:user', function(req, res, next) { + app.get('/foo/:user', function (req, res, next) { count++; next(); }); - app.use(function(req, res) { + app.use(function (req, res) { res.end([count, called, req.users.join(',')].join(' ')); }); - request(app) - .get('/foo/bob') - .expect('2 2 foo,bob', done); - }) + request(app).get('/foo/bob').expect('2 2 foo,bob', done); + }); - it('should support altering req.params across routes', function(done) { + it('should support altering req.params across routes', function (done) { var app = express(); - app.param('user', function(req, res, next, user) { + app.param('user', function (req, res, next, user) { req.params.user = 'loki'; next(); }); - app.get('/:user', function(req, res, next) { + app.get('/:user', function (req, res, next) { next('route'); }); app.get('/:user', function (req, res) { res.send(req.params.user); }); - request(app) - .get('/bob') - .expect('loki', done); - }) + request(app).get('/bob').expect('loki', done); + }); - it('should not invoke without route handler', function(done) { + it('should not invoke without route handler', function (done) { var app = express(); - app.param('thing', function(req, res, next, thing) { + app.param('thing', function (req, res, next, thing) { req.thing = thing; next(); }); - app.param('user', function(req, res, next, user) { - next(new Error('invalid invocation')) + app.param('user', function (req, res, next, user) { + next(new Error('invalid invocation')); }); app.post('/:user', function (req, res) { @@ -153,171 +143,155 @@ describe('app', function(){ res.send(req.thing); }); - request(app) - .get('/bob') - .expect(200, 'bob', done); - }) + request(app).get('/bob').expect(200, 'bob', done); + }); - it('should work with encoded values', function(done){ + it('should work with encoded values', function (done) { var app = express(); - app.param('name', function(req, res, next, name){ + app.param('name', function (req, res, next, name) { req.params.name = name; next(); }); - app.get('/user/:name', function(req, res){ + app.get('/user/:name', function (req, res) { var name = req.params.name; res.send('' + name); }); - request(app) - .get('/user/foo%25bar') - .expect('foo%bar', done); - }) + request(app).get('/user/foo%25bar').expect('foo%bar', done); + }); - it('should catch thrown error', function(done){ + it('should catch thrown error', function (done) { var app = express(); - app.param('id', function(req, res, next, id){ + app.param('id', function (req, res, next, id) { throw new Error('err!'); }); - app.get('/user/:id', function(req, res){ + app.get('/user/:id', function (req, res) { var id = req.params.id; res.send('' + id); }); - request(app) - .get('/user/123') - .expect(500, done); - }) + request(app).get('/user/123').expect(500, done); + }); - it('should catch thrown secondary error', function(done){ + it('should catch thrown secondary error', function (done) { var app = express(); - app.param('id', function(req, res, next, val){ + app.param('id', function (req, res, next, val) { process.nextTick(next); }); - app.param('id', function(req, res, next, id){ + app.param('id', function (req, res, next, id) { throw new Error('err!'); }); - app.get('/user/:id', function(req, res){ + app.get('/user/:id', function (req, res) { var id = req.params.id; res.send('' + id); }); - request(app) - .get('/user/123') - .expect(500, done); - }) + request(app).get('/user/123').expect(500, done); + }); - it('should defer to next route', function(done){ + it('should defer to next route', function (done) { var app = express(); - app.param('id', function(req, res, next, id){ + app.param('id', function (req, res, next, id) { next('route'); }); - app.get('/user/:id', function(req, res){ + app.get('/user/:id', function (req, res) { var id = req.params.id; res.send('' + id); }); - app.get('/:name/123', function(req, res){ + app.get('/:name/123', function (req, res) { res.send('name'); }); - request(app) - .get('/user/123') - .expect('name', done); - }) + request(app).get('/user/123').expect('name', done); + }); - it('should defer all the param routes', function(done){ + it('should defer all the param routes', function (done) { var app = express(); - app.param('id', function(req, res, next, val){ + app.param('id', function (req, res, next, val) { if (val === 'new') return next('route'); return next(); }); - app.all('/user/:id', function(req, res){ + app.all('/user/:id', function (req, res) { res.send('all.id'); }); - app.get('/user/:id', function(req, res){ + app.get('/user/:id', function (req, res) { res.send('get.id'); }); - app.get('/user/new', function(req, res){ + app.get('/user/new', function (req, res) { res.send('get.new'); }); - request(app) - .get('/user/new') - .expect('get.new', done); - }) + request(app).get('/user/new').expect('get.new', done); + }); - it('should not call when values differ on error', function(done) { + it('should not call when values differ on error', function (done) { var app = express(); var called = 0; var count = 0; - app.param('user', function(req, res, next, user) { + app.param('user', function (req, res, next, user) { called++; if (user === 'foo') throw new Error('err!'); req.user = user; next(); }); - app.get('/:user/bob', function(req, res, next) { + app.get('/:user/bob', function (req, res, next) { count++; next(); }); - app.get('/foo/:user', function(req, res, next) { + app.get('/foo/:user', function (req, res, next) { count++; next(); }); - app.use(function(err, req, res, next) { + app.use(function (err, req, res, next) { res.status(500); res.send([count, called, err.message].join(' ')); }); - request(app) - .get('/foo/bob') - .expect(500, '0 1 err!', done) + request(app).get('/foo/bob').expect(500, '0 1 err!', done); }); - it('should call when values differ when using "next"', function(done) { + it('should call when values differ when using "next"', function (done) { var app = express(); var called = 0; var count = 0; - app.param('user', function(req, res, next, user) { + app.param('user', function (req, res, next, user) { called++; if (user === 'foo') return next('route'); req.user = user; next(); }); - app.get('/:user/bob', function(req, res, next) { + app.get('/:user/bob', function (req, res, next) { count++; next(); }); - app.get('/foo/:user', function(req, res, next) { + app.get('/foo/:user', function (req, res, next) { count++; next(); }); - app.use(function(req, res) { + app.use(function (req, res) { res.end([count, called, req.user].join(' ')); }); - request(app) - .get('/foo/bob') - .expect('1 2 bob', done); - }) - }) -}) + request(app).get('/foo/bob').expect('1 2 bob', done); + }); + }); +}); diff --git a/test/app.render.js b/test/app.render.js index 9d202acfdda..c7ac34d52b5 100644 --- a/test/app.render.js +++ b/test/app.render.js @@ -1,25 +1,28 @@ -'use strict' +'use strict'; -var assert = require('assert') +var assert = require('assert'); var express = require('..'); -var path = require('path') +var path = require('path'); var tmpl = require('./support/tmpl'); -describe('app', function(){ - describe('.render(name, fn)', function(){ - it('should support absolute paths', function(done){ +describe('app', function () { + describe('.render(name, fn)', function () { + it('should support absolute paths', function (done) { var app = createApp(); app.locals.user = { name: 'tobi' }; - app.render(path.join(__dirname, 'fixtures', 'user.tmpl'), function (err, str) { - if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') - done(); - }) - }) + app.render( + path.join(__dirname, 'fixtures', 'user.tmpl'), + function (err, str) { + if (err) return done(err); + assert.strictEqual(str, '

        tobi

        '); + done(); + }, + ); + }); - it('should support absolute paths with "view engine"', function(done){ + it('should support absolute paths with "view engine"', function (done) { var app = createApp(); app.set('view engine', 'tmpl'); @@ -27,343 +30,356 @@ describe('app', function(){ app.render(path.join(__dirname, 'fixtures', 'user'), function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) + }); + }); - it('should expose app.locals', function(done){ + it('should expose app.locals', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.locals.user = { name: 'tobi' }; app.render('user.tmpl', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) + }); + }); - it('should support index.', function(done){ + it('should support index.', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.set('view engine', 'tmpl'); app.render('blog/post', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        blog post

        ') + assert.strictEqual(str, '

        blog post

        '); done(); - }) - }) + }); + }); - it('should handle render error throws', function(done){ + it('should handle render error throws', function (done) { var app = express(); - function View(name, options){ + function View(name, options) { this.name = name; this.path = 'fale'; } - View.prototype.render = function(options, fn){ + View.prototype.render = function (options, fn) { throw new Error('err!'); }; app.set('view', View); - app.render('something', function(err, str){ - assert.ok(err) - assert.strictEqual(err.message, 'err!') + app.render('something', function (err, str) { + assert.ok(err); + assert.strictEqual(err.message, 'err!'); done(); - }) - }) + }); + }); - describe('when the file does not exist', function(){ - it('should provide a helpful error', function(done){ + describe('when the file does not exist', function () { + it('should provide a helpful error', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.render('rawr.tmpl', function (err) { - assert.ok(err) - assert.equal(err.message, 'Failed to lookup view "rawr.tmpl" in views directory "' + path.join(__dirname, 'fixtures') + '"') + assert.ok(err); + assert.equal( + err.message, + 'Failed to lookup view "rawr.tmpl" in views directory "' + + path.join(__dirname, 'fixtures') + + '"', + ); done(); }); - }) - }) + }); + }); - describe('when an error occurs', function(){ - it('should invoke the callback', function(done){ + describe('when an error occurs', function () { + it('should invoke the callback', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.render('user.tmpl', function (err) { - assert.ok(err) - assert.equal(err.name, 'RenderError') - done() - }) - }) - }) - - describe('when an extension is given', function(){ - it('should render the template', function(done){ + assert.ok(err); + assert.equal(err.name, 'RenderError'); + done(); + }); + }); + }); + + describe('when an extension is given', function () { + it('should render the template', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.render('email.tmpl', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        This is an email

        ') + assert.strictEqual(str, '

        This is an email

        '); done(); - }) - }) - }) + }); + }); + }); - describe('when "view engine" is given', function(){ - it('should render the template', function(done){ + describe('when "view engine" is given', function () { + it('should render the template', function (done) { var app = createApp(); app.set('view engine', 'tmpl'); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); - app.render('email', function(err, str){ + app.render('email', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        This is an email

        ') + assert.strictEqual(str, '

        This is an email

        '); done(); - }) - }) - }) + }); + }); + }); - describe('when "views" is given', function(){ - it('should lookup the file in the path', function(done){ + describe('when "views" is given', function () { + it('should lookup the file in the path', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures', 'default_layout')) + app.set('views', path.join(__dirname, 'fixtures', 'default_layout')); app.locals.user = { name: 'tobi' }; app.render('user.tmpl', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) + }); + }); - describe('when array of paths', function(){ - it('should lookup the file in the path', function(done){ + describe('when array of paths', function () { + it('should lookup the file in the path', function (done) { var app = createApp(); var views = [ path.join(__dirname, 'fixtures', 'local_layout'), - path.join(__dirname, 'fixtures', 'default_layout') - ] + path.join(__dirname, 'fixtures', 'default_layout'), + ]; app.set('views', views); app.locals.user = { name: 'tobi' }; app.render('user.tmpl', function (err, str) { if (err) return done(err); - assert.strictEqual(str, 'tobi') + assert.strictEqual(str, 'tobi'); done(); - }) - }) + }); + }); - it('should lookup in later paths until found', function(done){ + it('should lookup in later paths until found', function (done) { var app = createApp(); var views = [ path.join(__dirname, 'fixtures', 'local_layout'), - path.join(__dirname, 'fixtures', 'default_layout') - ] + path.join(__dirname, 'fixtures', 'default_layout'), + ]; app.set('views', views); app.locals.name = 'tobi'; app.render('name.tmpl', function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) + }); + }); - it('should error if file does not exist', function(done){ + it('should error if file does not exist', function (done) { var app = createApp(); var views = [ path.join(__dirname, 'fixtures', 'local_layout'), - path.join(__dirname, 'fixtures', 'default_layout') - ] + path.join(__dirname, 'fixtures', 'default_layout'), + ]; app.set('views', views); app.locals.name = 'tobi'; app.render('pet.tmpl', function (err, str) { - assert.ok(err) - assert.equal(err.message, 'Failed to lookup view "pet.tmpl" in views directories "' + views[0] + '" or "' + views[1] + '"') + assert.ok(err); + assert.equal( + err.message, + 'Failed to lookup view "pet.tmpl" in views directories "' + + views[0] + + '" or "' + + views[1] + + '"', + ); done(); - }) - }) - }) - }) + }); + }); + }); + }); - describe('when a "view" constructor is given', function(){ - it('should create an instance of it', function(done){ + describe('when a "view" constructor is given', function () { + it('should create an instance of it', function (done) { var app = express(); - function View(name, options){ + function View(name, options) { this.name = name; - this.path = 'path is required by application.js as a signal of success even though it is not used there.'; + this.path = + 'path is required by application.js as a signal of success even though it is not used there.'; } - View.prototype.render = function(options, fn){ + View.prototype.render = function (options, fn) { fn(null, 'abstract engine'); }; app.set('view', View); - app.render('something', function(err, str){ + app.render('something', function (err, str) { if (err) return done(err); - assert.strictEqual(str, 'abstract engine') + assert.strictEqual(str, 'abstract engine'); done(); - }) - }) - }) + }); + }); + }); - describe('caching', function(){ - it('should always lookup view without cache', function(done){ + describe('caching', function () { + it('should always lookup view without cache', function (done) { var app = express(); var count = 0; - function View(name, options){ + function View(name, options) { this.name = name; this.path = 'fake'; count++; } - View.prototype.render = function(options, fn){ + View.prototype.render = function (options, fn) { fn(null, 'abstract engine'); }; app.set('view cache', false); app.set('view', View); - app.render('something', function(err, str){ + app.render('something', function (err, str) { if (err) return done(err); - assert.strictEqual(count, 1) - assert.strictEqual(str, 'abstract engine') - app.render('something', function(err, str){ + assert.strictEqual(count, 1); + assert.strictEqual(str, 'abstract engine'); + app.render('something', function (err, str) { if (err) return done(err); - assert.strictEqual(count, 2) - assert.strictEqual(str, 'abstract engine') + assert.strictEqual(count, 2); + assert.strictEqual(str, 'abstract engine'); done(); - }) - }) - }) + }); + }); + }); - it('should cache with "view cache" setting', function(done){ + it('should cache with "view cache" setting', function (done) { var app = express(); var count = 0; - function View(name, options){ + function View(name, options) { this.name = name; this.path = 'fake'; count++; } - View.prototype.render = function(options, fn){ + View.prototype.render = function (options, fn) { fn(null, 'abstract engine'); }; app.set('view cache', true); app.set('view', View); - app.render('something', function(err, str){ + app.render('something', function (err, str) { if (err) return done(err); - assert.strictEqual(count, 1) - assert.strictEqual(str, 'abstract engine') - app.render('something', function(err, str){ + assert.strictEqual(count, 1); + assert.strictEqual(str, 'abstract engine'); + app.render('something', function (err, str) { if (err) return done(err); - assert.strictEqual(count, 1) - assert.strictEqual(str, 'abstract engine') + assert.strictEqual(count, 1); + assert.strictEqual(str, 'abstract engine'); done(); - }) - }) - }) - }) - }) - - describe('.render(name, options, fn)', function(){ - it('should render the template', function(done){ + }); + }); + }); + }); + }); + + describe('.render(name, options, fn)', function () { + it('should render the template', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); var user = { name: 'tobi' }; app.render('user.tmpl', { user: user }, function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) + }); + }); - it('should expose app.locals', function(done){ + it('should expose app.locals', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.locals.user = { name: 'tobi' }; app.render('user.tmpl', {}, function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        tobi

        ') + assert.strictEqual(str, '

        tobi

        '); done(); - }) - }) + }); + }); - it('should give precedence to app.render() locals', function(done){ + it('should give precedence to app.render() locals', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.locals.user = { name: 'tobi' }; var jane = { name: 'jane' }; app.render('user.tmpl', { user: jane }, function (err, str) { if (err) return done(err); - assert.strictEqual(str, '

        jane

        ') + assert.strictEqual(str, '

        jane

        '); done(); - }) - }) + }); + }); - describe('caching', function(){ - it('should cache with cache option', function(done){ + describe('caching', function () { + it('should cache with cache option', function (done) { var app = express(); var count = 0; - function View(name, options){ + function View(name, options) { this.name = name; this.path = 'fake'; count++; } - View.prototype.render = function(options, fn){ + View.prototype.render = function (options, fn) { fn(null, 'abstract engine'); }; app.set('view cache', false); app.set('view', View); - app.render('something', {cache: true}, function(err, str){ + app.render('something', { cache: true }, function (err, str) { if (err) return done(err); - assert.strictEqual(count, 1) - assert.strictEqual(str, 'abstract engine') - app.render('something', {cache: true}, function(err, str){ + assert.strictEqual(count, 1); + assert.strictEqual(str, 'abstract engine'); + app.render('something', { cache: true }, function (err, str) { if (err) return done(err); - assert.strictEqual(count, 1) - assert.strictEqual(str, 'abstract engine') + assert.strictEqual(count, 1); + assert.strictEqual(str, 'abstract engine'); done(); - }) - }) - }) - }) - }) -}) + }); + }); + }); + }); + }); +}); function createApp() { var app = express(); diff --git a/test/app.request.js b/test/app.request.js index 4930af84c25..7ded53ec916 100644 --- a/test/app.request.js +++ b/test/app.request.js @@ -1,143 +1,127 @@ -'use strict' +'use strict'; -var after = require('after') -var express = require('../') - , request = require('supertest'); +var after = require('after'); +var express = require('../'), + request = require('supertest'); -describe('app', function(){ - describe('.request', function(){ - it('should extend the request prototype', function(done){ +describe('app', function () { + describe('.request', function () { + it('should extend the request prototype', function (done) { var app = express(); - app.request.querystring = function(){ + app.request.querystring = function () { return require('url').parse(this.url).query; }; - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.querystring()); }); - request(app) - .get('/foo?name=tobi') - .expect('name=tobi', done); - }) + request(app).get('/foo?name=tobi').expect('name=tobi', done); + }); it('should only extend for the referenced app', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + var app1 = express(); + var app2 = express(); + var cb = after(2, done); app1.request.foobar = function () { - return 'tobi' - } + return 'tobi'; + }; app1.get('/', function (req, res) { - res.send(req.foobar()) - }) + res.send(req.foobar()); + }); app2.get('/', function (req, res) { - res.send(req.foobar()) - }) + res.send(req.foobar()); + }); - request(app1) - .get('/') - .expect(200, 'tobi', cb) + request(app1).get('/').expect(200, 'tobi', cb); request(app2) .get('/') - .expect(500, /(?:not a function|has no method)/, cb) - }) + .expect(500, /(?:not a function|has no method)/, cb); + }); it('should inherit to sub apps', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + var app1 = express(); + var app2 = express(); + var cb = after(2, done); app1.request.foobar = function () { - return 'tobi' - } + return 'tobi'; + }; - app1.use('/sub', app2) + app1.use('/sub', app2); app1.get('/', function (req, res) { - res.send(req.foobar()) - }) + res.send(req.foobar()); + }); app2.get('/', function (req, res) { - res.send(req.foobar()) - }) + res.send(req.foobar()); + }); - request(app1) - .get('/') - .expect(200, 'tobi', cb) + request(app1).get('/').expect(200, 'tobi', cb); - request(app1) - .get('/sub') - .expect(200, 'tobi', cb) - }) + request(app1).get('/sub').expect(200, 'tobi', cb); + }); it('should allow sub app to override', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + var app1 = express(); + var app2 = express(); + var cb = after(2, done); app1.request.foobar = function () { - return 'tobi' - } + return 'tobi'; + }; app2.request.foobar = function () { - return 'loki' - } + return 'loki'; + }; - app1.use('/sub', app2) + app1.use('/sub', app2); app1.get('/', function (req, res) { - res.send(req.foobar()) - }) + res.send(req.foobar()); + }); app2.get('/', function (req, res) { - res.send(req.foobar()) - }) + res.send(req.foobar()); + }); - request(app1) - .get('/') - .expect(200, 'tobi', cb) + request(app1).get('/').expect(200, 'tobi', cb); - request(app1) - .get('/sub') - .expect(200, 'loki', cb) - }) + request(app1).get('/sub').expect(200, 'loki', cb); + }); it('should not pollute parent app', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + var app1 = express(); + var app2 = express(); + var cb = after(2, done); app1.request.foobar = function () { - return 'tobi' - } + return 'tobi'; + }; app2.request.foobar = function () { - return 'loki' - } + return 'loki'; + }; - app1.use('/sub', app2) + app1.use('/sub', app2); app1.get('/sub/foo', function (req, res) { - res.send(req.foobar()) - }) + res.send(req.foobar()); + }); app2.get('/', function (req, res) { - res.send(req.foobar()) - }) - - request(app1) - .get('/sub') - .expect(200, 'loki', cb) - - request(app1) - .get('/sub/foo') - .expect(200, 'tobi', cb) - }) - }) -}) + res.send(req.foobar()); + }); + + request(app1).get('/sub').expect(200, 'loki', cb); + + request(app1).get('/sub/foo').expect(200, 'tobi', cb); + }); + }); +}); diff --git a/test/app.response.js b/test/app.response.js index 5fb69f6275a..28f733125ed 100644 --- a/test/app.response.js +++ b/test/app.response.js @@ -1,143 +1,127 @@ -'use strict' +'use strict'; -var after = require('after') -var express = require('../') - , request = require('supertest'); +var after = require('after'); +var express = require('../'), + request = require('supertest'); -describe('app', function(){ - describe('.response', function(){ - it('should extend the response prototype', function(done){ +describe('app', function () { + describe('.response', function () { + it('should extend the response prototype', function (done) { var app = express(); - app.response.shout = function(str){ + app.response.shout = function (str) { this.send(str.toUpperCase()); }; - app.use(function(req, res){ + app.use(function (req, res) { res.shout('hey'); }); - request(app) - .get('/') - .expect('HEY', done); - }) + request(app).get('/').expect('HEY', done); + }); it('should only extend for the referenced app', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + var app1 = express(); + var app2 = express(); + var cb = after(2, done); app1.response.shout = function (str) { - this.send(str.toUpperCase()) - } + this.send(str.toUpperCase()); + }; app1.get('/', function (req, res) { - res.shout('foo') - }) + res.shout('foo'); + }); app2.get('/', function (req, res) { - res.shout('foo') - }) + res.shout('foo'); + }); - request(app1) - .get('/') - .expect(200, 'FOO', cb) + request(app1).get('/').expect(200, 'FOO', cb); request(app2) .get('/') - .expect(500, /(?:not a function|has no method)/, cb) - }) + .expect(500, /(?:not a function|has no method)/, cb); + }); it('should inherit to sub apps', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + var app1 = express(); + var app2 = express(); + var cb = after(2, done); app1.response.shout = function (str) { - this.send(str.toUpperCase()) - } + this.send(str.toUpperCase()); + }; - app1.use('/sub', app2) + app1.use('/sub', app2); app1.get('/', function (req, res) { - res.shout('foo') - }) + res.shout('foo'); + }); app2.get('/', function (req, res) { - res.shout('foo') - }) + res.shout('foo'); + }); - request(app1) - .get('/') - .expect(200, 'FOO', cb) + request(app1).get('/').expect(200, 'FOO', cb); - request(app1) - .get('/sub') - .expect(200, 'FOO', cb) - }) + request(app1).get('/sub').expect(200, 'FOO', cb); + }); it('should allow sub app to override', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + var app1 = express(); + var app2 = express(); + var cb = after(2, done); app1.response.shout = function (str) { - this.send(str.toUpperCase()) - } + this.send(str.toUpperCase()); + }; app2.response.shout = function (str) { - this.send(str + '!') - } + this.send(str + '!'); + }; - app1.use('/sub', app2) + app1.use('/sub', app2); app1.get('/', function (req, res) { - res.shout('foo') - }) + res.shout('foo'); + }); app2.get('/', function (req, res) { - res.shout('foo') - }) + res.shout('foo'); + }); - request(app1) - .get('/') - .expect(200, 'FOO', cb) + request(app1).get('/').expect(200, 'FOO', cb); - request(app1) - .get('/sub') - .expect(200, 'foo!', cb) - }) + request(app1).get('/sub').expect(200, 'foo!', cb); + }); it('should not pollute parent app', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + var app1 = express(); + var app2 = express(); + var cb = after(2, done); app1.response.shout = function (str) { - this.send(str.toUpperCase()) - } + this.send(str.toUpperCase()); + }; app2.response.shout = function (str) { - this.send(str + '!') - } + this.send(str + '!'); + }; - app1.use('/sub', app2) + app1.use('/sub', app2); app1.get('/sub/foo', function (req, res) { - res.shout('foo') - }) + res.shout('foo'); + }); app2.get('/', function (req, res) { - res.shout('foo') - }) - - request(app1) - .get('/sub') - .expect(200, 'foo!', cb) - - request(app1) - .get('/sub/foo') - .expect(200, 'FOO', cb) - }) - }) -}) + res.shout('foo'); + }); + + request(app1).get('/sub').expect(200, 'foo!', cb); + + request(app1).get('/sub/foo').expect(200, 'FOO', cb); + }); + }); +}); diff --git a/test/app.route.js b/test/app.route.js index a0c8696e509..3b09a3e423c 100644 --- a/test/app.route.js +++ b/test/app.route.js @@ -1,199 +1,184 @@ -'use strict' +'use strict'; var express = require('../'); var request = require('supertest'); -var describePromises = global.Promise ? describe : describe.skip +var describePromises = global.Promise ? describe : describe.skip; -describe('app.route', function(){ - it('should return a new route', function(done){ +describe('app.route', function () { + it('should return a new route', function (done) { var app = express(); - app.route('/foo') - .get(function(req, res) { - res.send('get'); - }) - .post(function(req, res) { - res.send('post'); - }); + app + .route('/foo') + .get(function (req, res) { + res.send('get'); + }) + .post(function (req, res) { + res.send('post'); + }); - request(app) - .post('/foo') - .expect('post', done); + request(app).post('/foo').expect('post', done); }); - it('should all .VERB after .all', function(done){ + it('should all .VERB after .all', function (done) { var app = express(); - app.route('/foo') - .all(function(req, res, next) { - next(); - }) - .get(function(req, res) { - res.send('get'); - }) - .post(function(req, res) { - res.send('post'); - }); + app + .route('/foo') + .all(function (req, res, next) { + next(); + }) + .get(function (req, res) { + res.send('get'); + }) + .post(function (req, res) { + res.send('post'); + }); - request(app) - .post('/foo') - .expect('post', done); + request(app).post('/foo').expect('post', done); }); - it('should support dynamic routes', function(done){ + it('should support dynamic routes', function (done) { var app = express(); - app.route('/:foo') - .get(function(req, res) { + app.route('/:foo').get(function (req, res) { res.send(req.params.foo); }); - request(app) - .get('/test') - .expect('test', done); + request(app).get('/test').expect('test', done); }); - it('should not error on empty routes', function(done){ + it('should not error on empty routes', function (done) { var app = express(); app.route('/:foo'); - request(app) - .get('/test') - .expect(404, done); + request(app).get('/test').expect(404, done); }); describePromises('promise support', function () { it('should pass rejected promise value', function (done) { - var app = express() - var route = app.route('/foo') + var app = express(); + var route = app.route('/foo'); - route.all(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + route.all(function createError(req, res, next) { + return Promise.reject(new Error('boom!')); + }); - route.all(function helloWorld (req, res) { - res.send('hello, world!') - }) + route.all(function helloWorld(req, res) { + res.send('hello, world!'); + }); - route.all(function handleError (err, req, res, next) { - res.status(500) - res.send('caught: ' + err.message) - }) + route.all(function handleError(err, req, res, next) { + res.status(500); + res.send('caught: ' + err.message); + }); - request(app) - .get('/foo') - .expect(500, 'caught: boom!', done) - }) + request(app).get('/foo').expect(500, 'caught: boom!', done); + }); it('should pass rejected promise without value', function (done) { - var app = express() - var route = app.route('/foo') + var app = express(); + var route = app.route('/foo'); - route.all(function createError (req, res, next) { - return Promise.reject() - }) + route.all(function createError(req, res, next) { + return Promise.reject(); + }); - route.all(function helloWorld (req, res) { - res.send('hello, world!') - }) + route.all(function helloWorld(req, res) { + res.send('hello, world!'); + }); - route.all(function handleError (err, req, res, next) { - res.status(500) - res.send('caught: ' + err.message) - }) + route.all(function handleError(err, req, res, next) { + res.status(500); + res.send('caught: ' + err.message); + }); - request(app) - .get('/foo') - .expect(500, 'caught: Rejected promise', done) - }) + request(app).get('/foo').expect(500, 'caught: Rejected promise', done); + }); it('should ignore resolved promise', function (done) { - var app = express() - var route = app.route('/foo') + var app = express(); + var route = app.route('/foo'); - route.all(function createError (req, res, next) { - res.send('saw GET /foo') - return Promise.resolve('foo') - }) + route.all(function createError(req, res, next) { + res.send('saw GET /foo'); + return Promise.resolve('foo'); + }); route.all(function () { - done(new Error('Unexpected route invoke')) - }) + done(new Error('Unexpected route invoke')); + }); - request(app) - .get('/foo') - .expect(200, 'saw GET /foo', done) - }) + request(app).get('/foo').expect(200, 'saw GET /foo', done); + }); describe('error handling', function () { it('should pass rejected promise value', function (done) { - var app = express() - var route = app.route('/foo') + var app = express(); + var route = app.route('/foo'); - route.all(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + route.all(function createError(req, res, next) { + return Promise.reject(new Error('boom!')); + }); - route.all(function handleError (err, req, res, next) { - return Promise.reject(new Error('caught: ' + err.message)) - }) + route.all(function handleError(err, req, res, next) { + return Promise.reject(new Error('caught: ' + err.message)); + }); - route.all(function handleError (err, req, res, next) { - res.status(500) - res.send('caught again: ' + err.message) - }) + route.all(function handleError(err, req, res, next) { + res.status(500); + res.send('caught again: ' + err.message); + }); request(app) - .get('/foo') - .expect(500, 'caught again: caught: boom!', done) - }) + .get('/foo') + .expect(500, 'caught again: caught: boom!', done); + }); it('should pass rejected promise without value', function (done) { - var app = express() - var route = app.route('/foo') + var app = express(); + var route = app.route('/foo'); - route.all(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + route.all(function createError(req, res, next) { + return Promise.reject(new Error('boom!')); + }); - route.all(function handleError (err, req, res, next) { - return Promise.reject() - }) + route.all(function handleError(err, req, res, next) { + return Promise.reject(); + }); - route.all(function handleError (err, req, res, next) { - res.status(500) - res.send('caught again: ' + err.message) - }) + route.all(function handleError(err, req, res, next) { + res.status(500); + res.send('caught again: ' + err.message); + }); request(app) - .get('/foo') - .expect(500, 'caught again: Rejected promise', done) - }) + .get('/foo') + .expect(500, 'caught again: Rejected promise', done); + }); it('should ignore resolved promise', function (done) { - var app = express() - var route = app.route('/foo') + var app = express(); + var route = app.route('/foo'); - route.all(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + route.all(function createError(req, res, next) { + return Promise.reject(new Error('boom!')); + }); - route.all(function handleError (err, req, res, next) { - res.status(500) - res.send('caught: ' + err.message) - return Promise.resolve('foo') - }) + route.all(function handleError(err, req, res, next) { + res.status(500); + res.send('caught: ' + err.message); + return Promise.resolve('foo'); + }); route.all(function () { - done(new Error('Unexpected route invoke')) - }) + done(new Error('Unexpected route invoke')); + }); - request(app) - .get('/foo') - .expect(500, 'caught: boom!', done) - }) - }) - }) + request(app).get('/foo').expect(500, 'caught: boom!', done); + }); + }); + }); }); diff --git a/test/app.router.js b/test/app.router.js index 1db40042a1c..930230084fa 100644 --- a/test/app.router.js +++ b/test/app.router.js @@ -1,29 +1,29 @@ -'use strict' +'use strict'; var after = require('after'); -var express = require('../') - , request = require('supertest') - , assert = require('assert') - , methods = require('methods'); +var express = require('../'), + request = require('supertest'), + assert = require('assert'), + methods = require('methods'); -var describePromises = global.Promise ? describe : describe.skip -var shouldSkipQuery = require('./support/utils').shouldSkipQuery +var describePromises = global.Promise ? describe : describe.skip; +var shouldSkipQuery = require('./support/utils').shouldSkipQuery; -describe('app.router', function(){ - it('should restore req.params after leaving router', function(done){ +describe('app.router', function () { + it('should restore req.params after leaving router', function (done) { var app = express(); var router = new express.Router(); - function handler1(req, res, next){ + function handler1(req, res, next) { res.setHeader('x-user-id', String(req.params.id)); - next() + next(); } - function handler2(req, res){ + function handler2(req, res) { res.send(req.params.id); } - router.use(function(req, res, next){ + router.use(function (req, res, next) { res.setHeader('x-router', String(req.params.id)); next(); }); @@ -31,35 +31,36 @@ describe('app.router', function(){ app.get('/user/:id', handler1, router, handler2); request(app) - .get('/user/1') - .expect('x-router', 'undefined') - .expect('x-user-id', '1') - .expect(200, '1', done); - }) - - describe('methods', function(){ - methods.forEach(function(method){ + .get('/user/1') + .expect('x-router', 'undefined') + .expect('x-user-id', '1') + .expect(200, '1', done); + }); + + describe('methods', function () { + methods.forEach(function (method) { if (method === 'connect') return; - it('should include ' + method.toUpperCase(), function(done){ + it('should include ' + method.toUpperCase(), function (done) { if (method === 'query' && shouldSkipQuery(process.versions.node)) { - this.skip() + this.skip(); } var app = express(); - app[method]('/foo', function(req, res){ - res.send(method) + app[method]('/foo', function (req, res) { + res.send(method); }); - request(app) - [method]('/foo') - .expect(200, done) - }) + request(app)[method]('/foo').expect(200, done); + }); - it('should reject numbers for app.' + method, function(){ + it('should reject numbers for app.' + method, function () { var app = express(); - assert.throws(app[method].bind(app, '/', 3), /argument handler must be a function/); - }) + assert.throws( + app[method].bind(app, '/', 3), + /argument handler must be a function/, + ); + }); }); it('should re-route when method is altered', function (done) { @@ -77,317 +78,311 @@ describe('app.router', function(){ res.end('deleted everything'); }); - request(app) - .get('/') - .expect(404, cb) + request(app).get('/').expect(404, cb); - request(app) - .delete('/') - .expect(200, 'deleted everything', cb); + request(app).delete('/').expect(200, 'deleted everything', cb); request(app) - .post('/') - .expect('X-Method-Altered', '1') - .expect(200, 'deleted everything', cb); + .post('/') + .expect('X-Method-Altered', '1') + .expect(200, 'deleted everything', cb); }); - }) + }); describe('decode params', function () { - it('should decode correct params', function(done){ + it('should decode correct params', function (done) { var app = express(); app.get('/:name', function (req, res) { res.send(req.params.name); }); - request(app) - .get('/foo%2Fbar') - .expect('foo/bar', done); - }) + request(app).get('/foo%2Fbar').expect('foo/bar', done); + }); - it('should not accept params in malformed paths', function(done) { + it('should not accept params in malformed paths', function (done) { var app = express(); app.get('/:name', function (req, res) { res.send(req.params.name); }); - request(app) - .get('/%foobar') - .expect(400, done); - }) + request(app).get('/%foobar').expect(400, done); + }); - it('should not decode spaces', function(done) { + it('should not decode spaces', function (done) { var app = express(); app.get('/:name', function (req, res) { res.send(req.params.name); }); - request(app) - .get('/foo+bar') - .expect('foo+bar', done); - }) + request(app).get('/foo+bar').expect('foo+bar', done); + }); - it('should work with unicode', function(done) { + it('should work with unicode', function (done) { var app = express(); app.get('/:name', function (req, res) { res.send(req.params.name); }); - request(app) - .get('/%ce%b1') - .expect('\u03b1', done); - }) - }) + request(app).get('/%ce%b1').expect('\u03b1', done); + }); + }); - it('should be .use()able', function(done){ + it('should be .use()able', function (done) { var app = express(); var calls = []; - app.use(function(req, res, next){ + app.use(function (req, res, next) { calls.push('before'); next(); }); - app.get('/', function(req, res, next){ - calls.push('GET /') + app.get('/', function (req, res, next) { + calls.push('GET /'); next(); }); - app.use(function(req, res, next){ + app.use(function (req, res, next) { calls.push('after'); - res.json(calls) + res.json(calls); }); - request(app) - .get('/') - .expect(200, ['before', 'GET /', 'after'], done) - }) + request(app).get('/').expect(200, ['before', 'GET /', 'after'], done); + }); - describe('when given a regexp', function(){ - it('should match the pathname only', function(done){ + describe('when given a regexp', function () { + it('should match the pathname only', function (done) { var app = express(); - app.get(/^\/user\/[0-9]+$/, function(req, res){ + app.get(/^\/user\/[0-9]+$/, function (req, res) { res.end('user'); }); - request(app) - .get('/user/12?foo=bar') - .expect('user', done); - }) + request(app).get('/user/12?foo=bar').expect('user', done); + }); - it('should populate req.params with the captures', function(done){ + it('should populate req.params with the captures', function (done) { var app = express(); - app.get(/^\/user\/([0-9]+)\/(view|edit)?$/, function(req, res){ - var id = req.params[0] - , op = req.params[1]; + app.get(/^\/user\/([0-9]+)\/(view|edit)?$/, function (req, res) { + var id = req.params[0], + op = req.params[1]; res.end(op + 'ing user ' + id); }); - request(app) - .get('/user/10/edit') - .expect('editing user 10', done); - }) + request(app).get('/user/10/edit').expect('editing user 10', done); + }); if (supportsRegexp('(?.*)')) { - it('should populate req.params with named captures', function(done){ + it('should populate req.params with named captures', function (done) { var app = express(); var re = new RegExp('^/user/(?[0-9]+)/(view|edit)?$'); - app.get(re, function(req, res){ - var id = req.params.userId - , op = req.params[0]; + app.get(re, function (req, res) { + var id = req.params.userId, + op = req.params[0]; res.end(op + 'ing user ' + id); }); - request(app) - .get('/user/10/edit') - .expect('editing user 10', done); - }) + request(app).get('/user/10/edit').expect('editing user 10', done); + }); } it('should ensure regexp matches path prefix', function (done) { - var app = express() - var p = [] + var app = express(); + var p = []; app.use(/\/api.*/, function (req, res, next) { - p.push('a') - next() - }) + p.push('a'); + next(); + }); app.use(/api/, function (req, res, next) { - p.push('b') - next() - }) + p.push('b'); + next(); + }); app.use(/\/test/, function (req, res, next) { - p.push('c') - next() - }) + p.push('c'); + next(); + }); app.use(function (req, res) { - res.end() - }) + res.end(); + }); request(app) .get('/test/api/1234') .expect(200, function (err) { - if (err) return done(err) - assert.deepEqual(p, ['c']) - done() - }) - }) - }) - - describe('case sensitivity', function(){ - it('should be disabled by default', function(done){ + if (err) return done(err); + assert.deepEqual(p, ['c']); + done(); + }); + }); + }); + + describe('case sensitivity', function () { + it('should be disabled by default', function (done) { var app = express(); - app.get('/user', function(req, res){ + app.get('/user', function (req, res) { res.end('tj'); }); - request(app) - .get('/USER') - .expect('tj', done); - }) + request(app).get('/USER').expect('tj', done); + }); - describe('when "case sensitive routing" is enabled', function(){ - it('should match identical casing', function(done){ + describe('when "case sensitive routing" is enabled', function () { + it('should match identical casing', function (done) { var app = express(); app.enable('case sensitive routing'); - app.get('/uSer', function(req, res){ + app.get('/uSer', function (req, res) { res.end('tj'); }); - request(app) - .get('/uSer') - .expect('tj', done); - }) + request(app).get('/uSer').expect('tj', done); + }); - it('should not match otherwise', function(done){ + it('should not match otherwise', function (done) { var app = express(); app.enable('case sensitive routing'); - app.get('/uSer', function(req, res){ + app.get('/uSer', function (req, res) { res.end('tj'); }); - request(app) - .get('/user') - .expect(404, done); - }) - }) - }) + request(app).get('/user').expect(404, done); + }); + }); + }); - describe('params', function(){ - it('should overwrite existing req.params by default', function(done){ + describe('params', function () { + it('should overwrite existing req.params by default', function (done) { var app = express(); var router = new express.Router(); - router.get('/:action', function(req, res){ + router.get('/:action', function (req, res) { res.send(req.params); }); app.use('/user/:user', router); - request(app) - .get('/user/1/get') - .expect(200, '{"action":"get"}', done); - }) + request(app).get('/user/1/get').expect(200, '{"action":"get"}', done); + }); - it('should allow merging existing req.params', function(done){ + it('should allow merging existing req.params', function (done) { var app = express(); var router = new express.Router({ mergeParams: true }); - router.get('/:action', function(req, res){ + router.get('/:action', function (req, res) { var keys = Object.keys(req.params).sort(); - res.send(keys.map(function(k){ return [k, req.params[k]] })); + res.send( + keys.map(function (k) { + return [k, req.params[k]]; + }), + ); }); app.use('/user/:user', router); request(app) - .get('/user/tj/get') - .expect(200, '[["action","get"],["user","tj"]]', done); - }) + .get('/user/tj/get') + .expect(200, '[["action","get"],["user","tj"]]', done); + }); - it('should use params from router', function(done){ + it('should use params from router', function (done) { var app = express(); var router = new express.Router({ mergeParams: true }); - router.get('/:thing', function(req, res){ + router.get('/:thing', function (req, res) { var keys = Object.keys(req.params).sort(); - res.send(keys.map(function(k){ return [k, req.params[k]] })); + res.send( + keys.map(function (k) { + return [k, req.params[k]]; + }), + ); }); app.use('/user/:thing', router); - request(app) - .get('/user/tj/get') - .expect(200, '[["thing","get"]]', done); - }) + request(app).get('/user/tj/get').expect(200, '[["thing","get"]]', done); + }); - it('should merge numeric indices req.params', function(done){ + it('should merge numeric indices req.params', function (done) { var app = express(); var router = new express.Router({ mergeParams: true }); router.get(/^\/(.*)\.(.*)/, function (req, res) { var keys = Object.keys(req.params).sort(); - res.send(keys.map(function(k){ return [k, req.params[k]] })); + res.send( + keys.map(function (k) { + return [k, req.params[k]]; + }), + ); }); app.use(/^\/user\/id:(\d+)/, router); request(app) - .get('/user/id:10/profile.json') - .expect(200, '[["0","10"],["1","profile"],["2","json"]]', done); - }) + .get('/user/id:10/profile.json') + .expect(200, '[["0","10"],["1","profile"],["2","json"]]', done); + }); - it('should merge numeric indices req.params when more in parent', function(done){ + it('should merge numeric indices req.params when more in parent', function (done) { var app = express(); var router = new express.Router({ mergeParams: true }); router.get(/\/(.*)/, function (req, res) { var keys = Object.keys(req.params).sort(); - res.send(keys.map(function(k){ return [k, req.params[k]] })); + res.send( + keys.map(function (k) { + return [k, req.params[k]]; + }), + ); }); app.use(/^\/user\/id:(\d+)\/name:(\w+)/, router); request(app) - .get('/user/id:10/name:tj/profile') - .expect(200, '[["0","10"],["1","tj"],["2","profile"]]', done); - }) + .get('/user/id:10/name:tj/profile') + .expect(200, '[["0","10"],["1","tj"],["2","profile"]]', done); + }); - it('should merge numeric indices req.params when parent has same number', function(done){ + it('should merge numeric indices req.params when parent has same number', function (done) { var app = express(); var router = new express.Router({ mergeParams: true }); - router.get(/\/name:(\w+)/, function(req, res){ + router.get(/\/name:(\w+)/, function (req, res) { var keys = Object.keys(req.params).sort(); - res.send(keys.map(function(k){ return [k, req.params[k]] })); + res.send( + keys.map(function (k) { + return [k, req.params[k]]; + }), + ); }); app.use(/\/user\/id:(\d+)/, router); request(app) - .get('/user/id:10/name:tj') - .expect(200, '[["0","10"],["1","tj"]]', done); - }) + .get('/user/id:10/name:tj') + .expect(200, '[["0","10"],["1","tj"]]', done); + }); - it('should ignore invalid incoming req.params', function(done){ + it('should ignore invalid incoming req.params', function (done) { var app = express(); var router = new express.Router({ mergeParams: true }); - router.get('/:name', function(req, res){ + router.get('/:name', function (req, res) { var keys = Object.keys(req.params).sort(); - res.send(keys.map(function(k){ return [k, req.params[k]] })); + res.send( + keys.map(function (k) { + return [k, req.params[k]]; + }), + ); }); app.use('/user/', function (req, res, next) { @@ -395,12 +390,10 @@ describe('app.router', function(){ router(req, res, next); }); - request(app) - .get('/user/tj') - .expect(200, '[["name","tj"]]', done); - }) + request(app).get('/user/tj').expect(200, '[["name","tj"]]', done); + }); - it('should restore req.params', function(done){ + it('should restore req.params', function (done) { var app = express(); var router = new express.Router({ mergeParams: true }); @@ -411,45 +404,45 @@ describe('app.router', function(){ app.use(/\/user\/id:(\d+)/, function (req, res, next) { router(req, res, function (err) { var keys = Object.keys(req.params).sort(); - res.send(keys.map(function(k){ return [k, req.params[k]] })); + res.send( + keys.map(function (k) { + return [k, req.params[k]]; + }), + ); }); }); request(app) - .get('/user/id:42/user:tj/profile') - .expect(200, '[["0","42"]]', done); - }) - }) + .get('/user/id:42/user:tj/profile') + .expect(200, '[["0","42"]]', done); + }); + }); - describe('trailing slashes', function(){ - it('should be optional by default', function(done){ + describe('trailing slashes', function () { + it('should be optional by default', function (done) { var app = express(); - app.get('/user', function(req, res){ + app.get('/user', function (req, res) { res.end('tj'); }); - request(app) - .get('/user/') - .expect('tj', done); - }) + request(app).get('/user/').expect('tj', done); + }); - describe('when "strict routing" is enabled', function(){ - it('should match trailing slashes', function(done){ + describe('when "strict routing" is enabled', function () { + it('should match trailing slashes', function (done) { var app = express(); app.enable('strict routing'); - app.get('/user/', function(req, res){ + app.get('/user/', function (req, res) { res.end('tj'); }); - request(app) - .get('/user/') - .expect('tj', done); - }) + request(app).get('/user/').expect('tj', done); + }); - it('should pass-though middleware', function(done){ + it('should pass-though middleware', function (done) { var app = express(); app.enable('strict routing'); @@ -459,17 +452,17 @@ describe('app.router', function(){ next(); }); - app.get('/user/', function(req, res){ + app.get('/user/', function (req, res) { res.end('tj'); }); request(app) - .get('/user/') - .expect('x-middleware', 'true') - .expect(200, 'tj', done); - }) + .get('/user/') + .expect('x-middleware', 'true') + .expect(200, 'tj', done); + }); - it('should pass-though mounted middleware', function(done){ + it('should pass-though mounted middleware', function (done) { var app = express(); app.enable('strict routing'); @@ -479,349 +472,300 @@ describe('app.router', function(){ next(); }); - app.get('/user/test/', function(req, res){ + app.get('/user/test/', function (req, res) { res.end('tj'); }); request(app) - .get('/user/test/') - .expect('x-middleware', 'true') - .expect(200, 'tj', done); - }) + .get('/user/test/') + .expect('x-middleware', 'true') + .expect(200, 'tj', done); + }); - it('should match no slashes', function(done){ + it('should match no slashes', function (done) { var app = express(); app.enable('strict routing'); - app.get('/user', function(req, res){ + app.get('/user', function (req, res) { res.end('tj'); }); - request(app) - .get('/user') - .expect('tj', done); - }) + request(app).get('/user').expect('tj', done); + }); - it('should match middleware when omitting the trailing slash', function(done){ + it('should match middleware when omitting the trailing slash', function (done) { var app = express(); app.enable('strict routing'); - app.use('/user/', function(req, res){ + app.use('/user/', function (req, res) { res.end('tj'); }); - request(app) - .get('/user') - .expect(200, 'tj', done); - }) + request(app).get('/user').expect(200, 'tj', done); + }); - it('should match middleware', function(done){ + it('should match middleware', function (done) { var app = express(); app.enable('strict routing'); - app.use('/user', function(req, res){ + app.use('/user', function (req, res) { res.end('tj'); }); - request(app) - .get('/user') - .expect(200, 'tj', done); - }) + request(app).get('/user').expect(200, 'tj', done); + }); - it('should match middleware when adding the trailing slash', function(done){ + it('should match middleware when adding the trailing slash', function (done) { var app = express(); app.enable('strict routing'); - app.use('/user', function(req, res){ + app.use('/user', function (req, res) { res.end('tj'); }); - request(app) - .get('/user/') - .expect(200, 'tj', done); - }) + request(app).get('/user/').expect(200, 'tj', done); + }); - it('should fail when omitting the trailing slash', function(done){ + it('should fail when omitting the trailing slash', function (done) { var app = express(); app.enable('strict routing'); - app.get('/user/', function(req, res){ + app.get('/user/', function (req, res) { res.end('tj'); }); - request(app) - .get('/user') - .expect(404, done); - }) + request(app).get('/user').expect(404, done); + }); - it('should fail when adding the trailing slash', function(done){ + it('should fail when adding the trailing slash', function (done) { var app = express(); app.enable('strict routing'); - app.get('/user', function(req, res){ + app.get('/user', function (req, res) { res.end('tj'); }); - request(app) - .get('/user/') - .expect(404, done); - }) - }) - }) + request(app).get('/user/').expect(404, done); + }); + }); + }); - it('should allow literal "."', function(done){ + it('should allow literal "."', function (done) { var app = express(); - app.get('/api/users/:from..:to', function(req, res){ - var from = req.params.from - , to = req.params.to; + app.get('/api/users/:from..:to', function (req, res) { + var from = req.params.from, + to = req.params.to; res.end('users from ' + from + ' to ' + to); }); - request(app) - .get('/api/users/1..50') - .expect('users from 1 to 50', done); - }) + request(app).get('/api/users/1..50').expect('users from 1 to 50', done); + }); - describe(':name', function(){ - it('should denote a capture group', function(done){ + describe(':name', function () { + it('should denote a capture group', function (done) { var app = express(); - app.get('/user/:user', function(req, res){ + app.get('/user/:user', function (req, res) { res.end(req.params.user); }); - request(app) - .get('/user/tj') - .expect('tj', done); - }) + request(app).get('/user/tj').expect('tj', done); + }); - it('should match a single segment only', function(done){ + it('should match a single segment only', function (done) { var app = express(); - app.get('/user/:user', function(req, res){ + app.get('/user/:user', function (req, res) { res.end(req.params.user); }); - request(app) - .get('/user/tj/edit') - .expect(404, done); - }) + request(app).get('/user/tj/edit').expect(404, done); + }); - it('should allow several capture groups', function(done){ + it('should allow several capture groups', function (done) { var app = express(); - app.get('/user/:user/:op', function(req, res){ + app.get('/user/:user/:op', function (req, res) { res.end(req.params.op + 'ing ' + req.params.user); }); - request(app) - .get('/user/tj/edit') - .expect('editing tj', done); - }) + request(app).get('/user/tj/edit').expect('editing tj', done); + }); - it('should work following a partial capture group', function(done){ + it('should work following a partial capture group', function (done) { var app = express(); var cb = after(2, done); - app.get('/user{s}/:user/:op', function(req, res){ - res.end(req.params.op + 'ing ' + req.params.user + (req.url.startsWith('/users') ? ' (old)' : '')); + app.get('/user{s}/:user/:op', function (req, res) { + res.end( + req.params.op + + 'ing ' + + req.params.user + + (req.url.startsWith('/users') ? ' (old)' : ''), + ); }); - request(app) - .get('/user/tj/edit') - .expect('editing tj', cb); + request(app).get('/user/tj/edit').expect('editing tj', cb); - request(app) - .get('/users/tj/edit') - .expect('editing tj (old)', cb); - }) + request(app).get('/users/tj/edit').expect('editing tj (old)', cb); + }); - it('should work inside literal parenthesis', function(done){ + it('should work inside literal parenthesis', function (done) { var app = express(); - app.get('/:user\\(:op\\)', function(req, res){ + app.get('/:user\\(:op\\)', function (req, res) { res.end(req.params.op + 'ing ' + req.params.user); }); - request(app) - .get('/tj(edit)') - .expect('editing tj', done); - }) + request(app).get('/tj(edit)').expect('editing tj', done); + }); - it('should work in array of paths', function(done){ + it('should work in array of paths', function (done) { var app = express(); var cb = after(2, done); - app.get(['/user/:user/poke', '/user/:user/pokes'], function(req, res){ + app.get(['/user/:user/poke', '/user/:user/pokes'], function (req, res) { res.end('poking ' + req.params.user); }); - request(app) - .get('/user/tj/poke') - .expect('poking tj', cb); + request(app).get('/user/tj/poke').expect('poking tj', cb); - request(app) - .get('/user/tj/pokes') - .expect('poking tj', cb); - }) - }) + request(app).get('/user/tj/pokes').expect('poking tj', cb); + }); + }); - describe(':name?', function(){ - it('should denote an optional capture group', function(done){ + describe(':name?', function () { + it('should denote an optional capture group', function (done) { var app = express(); - app.get('/user/:user{/:op}', function(req, res){ + app.get('/user/:user{/:op}', function (req, res) { var op = req.params.op || 'view'; res.end(op + 'ing ' + req.params.user); }); - request(app) - .get('/user/tj') - .expect('viewing tj', done); - }) + request(app).get('/user/tj').expect('viewing tj', done); + }); - it('should populate the capture group', function(done){ + it('should populate the capture group', function (done) { var app = express(); - app.get('/user/:user{/:op}', function(req, res){ + app.get('/user/:user{/:op}', function (req, res) { var op = req.params.op || 'view'; res.end(op + 'ing ' + req.params.user); }); - request(app) - .get('/user/tj/edit') - .expect('editing tj', done); - }) - }) + request(app).get('/user/tj/edit').expect('editing tj', done); + }); + }); describe(':name*', function () { it('should match one segment', function (done) { - var app = express() + var app = express(); app.get('/user/*user', function (req, res) { - res.end(req.params.user[0]) - }) + res.end(req.params.user[0]); + }); - request(app) - .get('/user/122') - .expect('122', done) - }) + request(app).get('/user/122').expect('122', done); + }); it('should match many segments', function (done) { - var app = express() + var app = express(); app.get('/user/*user', function (req, res) { - res.end(req.params.user.join('/')) - }) + res.end(req.params.user.join('/')); + }); - request(app) - .get('/user/1/2/3/4') - .expect('1/2/3/4', done) - }) + request(app).get('/user/1/2/3/4').expect('1/2/3/4', done); + }); it('should match zero segments', function (done) { - var app = express() + var app = express(); app.get('/user{/*user}', function (req, res) { - res.end(req.params.user) - }) + res.end(req.params.user); + }); - request(app) - .get('/user') - .expect('', done) - }) - }) + request(app).get('/user').expect('', done); + }); + }); describe(':name+', function () { it('should match one segment', function (done) { - var app = express() + var app = express(); app.get('/user/*user', function (req, res) { - res.end(req.params.user[0]) - }) + res.end(req.params.user[0]); + }); - request(app) - .get('/user/122') - .expect(200, '122', done) - }) + request(app).get('/user/122').expect(200, '122', done); + }); it('should match many segments', function (done) { - var app = express() + var app = express(); app.get('/user/*user', function (req, res) { - res.end(req.params.user.join('/')) - }) + res.end(req.params.user.join('/')); + }); - request(app) - .get('/user/1/2/3/4') - .expect(200, '1/2/3/4', done) - }) + request(app).get('/user/1/2/3/4').expect(200, '1/2/3/4', done); + }); it('should not match zero segments', function (done) { - var app = express() + var app = express(); app.get('/user/*user', function (req, res) { - res.end(req.params.user) - }) + res.end(req.params.user); + }); - request(app) - .get('/user') - .expect(404, done) - }) - }) + request(app).get('/user').expect(404, done); + }); + }); - describe('.:name', function(){ - it('should denote a format', function(done){ + describe('.:name', function () { + it('should denote a format', function (done) { var app = express(); - var cb = after(2, done) + var cb = after(2, done); - app.get('/:name.:format', function(req, res){ + app.get('/:name.:format', function (req, res) { res.end(req.params.name + ' as ' + req.params.format); }); - request(app) - .get('/foo.json') - .expect(200, 'foo as json', cb) + request(app).get('/foo.json').expect(200, 'foo as json', cb); - request(app) - .get('/foo') - .expect(404, cb) - }) - }) + request(app).get('/foo').expect(404, cb); + }); + }); - describe('.:name?', function(){ - it('should denote an optional format', function(done){ + describe('.:name?', function () { + it('should denote an optional format', function (done) { var app = express(); - var cb = after(2, done) + var cb = after(2, done); - app.get('/:name{.:format}', function(req, res){ + app.get('/:name{.:format}', function (req, res) { res.end(req.params.name + ' as ' + (req.params.format || 'html')); }); - request(app) - .get('/foo') - .expect(200, 'foo as html', cb) + request(app).get('/foo').expect(200, 'foo as html', cb); - request(app) - .get('/foo.json') - .expect(200, 'foo as json', cb) - }) - }) + request(app).get('/foo.json').expect(200, 'foo as json', cb); + }); + }); - describe('when next() is called', function(){ - it('should continue lookup', function(done){ - var app = express() - , calls = []; + describe('when next() is called', function () { + it('should continue lookup', function (done) { + var app = express(), + calls = []; - app.get('/foo{/:bar}', function(req, res, next){ + app.get('/foo{/:bar}', function (req, res, next) { calls.push('/foo/:bar?'); next(); }); @@ -830,83 +774,83 @@ describe('app.router', function(){ assert(0); }); - app.get('/foo', function(req, res, next){ + app.get('/foo', function (req, res, next) { calls.push('/foo'); next(); }); app.get('/foo', function (req, res) { calls.push('/foo 2'); - res.json(calls) + res.json(calls); }); request(app) - .get('/foo') - .expect(200, ['/foo/:bar?', '/foo', '/foo 2'], done) - }) - }) - - describe('when next("route") is called', function(){ - it('should jump to next route', function(done){ - var app = express() - - function fn(req, res, next){ - res.set('X-Hit', '1') - next('route') + .get('/foo') + .expect(200, ['/foo/:bar?', '/foo', '/foo 2'], done); + }); + }); + + describe('when next("route") is called', function () { + it('should jump to next route', function (done) { + var app = express(); + + function fn(req, res, next) { + res.set('X-Hit', '1'); + next('route'); } app.get('/foo', fn, function (req, res) { - res.end('failure') + res.end('failure'); }); - app.get('/foo', function(req, res){ - res.end('success') - }) + app.get('/foo', function (req, res) { + res.end('success'); + }); request(app) - .get('/foo') - .expect('X-Hit', '1') - .expect(200, 'success', done) - }) - }) + .get('/foo') + .expect('X-Hit', '1') + .expect(200, 'success', done); + }); + }); describe('when next("router") is called', function () { it('should jump out of router', function (done) { - var app = express() - var router = express.Router() + var app = express(); + var router = express.Router(); - function fn (req, res, next) { - res.set('X-Hit', '1') - next('router') + function fn(req, res, next) { + res.set('X-Hit', '1'); + next('router'); } router.get('/foo', fn, function (req, res) { - res.end('failure') - }) + res.end('failure'); + }); router.get('/foo', function (req, res) { - res.end('failure') - }) + res.end('failure'); + }); - app.use(router) + app.use(router); app.get('/foo', function (req, res) { - res.end('success') - }) + res.end('success'); + }); request(app) - .get('/foo') - .expect('X-Hit', '1') - .expect(200, 'success', done) - }) - }) - - describe('when next(err) is called', function(){ - it('should break out of app.router', function(done){ - var app = express() - , calls = []; - - app.get('/foo{/:bar}', function(req, res, next){ + .get('/foo') + .expect('X-Hit', '1') + .expect(200, 'success', done); + }); + }); + + describe('when next(err) is called', function () { + it('should break out of app.router', function (done) { + var app = express(), + calls = []; + + app.get('/foo{/:bar}', function (req, res, next) { calls.push('/foo/:bar?'); next(); }); @@ -915,7 +859,7 @@ describe('app.router', function(){ assert(0); }); - app.get('/foo', function(req, res, next){ + app.get('/foo', function (req, res, next) { calls.push('/foo'); next(new Error('fail')); }); @@ -924,19 +868,19 @@ describe('app.router', function(){ assert(0); }); - app.use(function(err, req, res, next){ + app.use(function (err, req, res, next) { res.json({ calls: calls, - error: err.message - }) - }) + error: err.message, + }); + }); request(app) - .get('/foo') - .expect(200, { calls: ['/foo/:bar?', '/foo'], error: 'fail' }, done) - }) + .get('/foo') + .expect(200, { calls: ['/foo/:bar?', '/foo'], error: 'fail' }, done); + }); - it('should call handler in same route, if exists', function(done){ + it('should call handler in same route, if exists', function (done) { var app = express(); function fn1(req, res, next) { @@ -955,165 +899,151 @@ describe('app.router', function(){ app.use(function (err, req, res, next) { res.end('error!'); - }) + }); - request(app) - .get('/foo') - .expect('route go boom!', done) - }) - }) + request(app).get('/foo').expect('route go boom!', done); + }); + }); describePromises('promise support', function () { it('should pass rejected promise value', function (done) { - var app = express() - var router = new express.Router() + var app = express(); + var router = new express.Router(); - router.use(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + router.use(function createError(req, res, next) { + return Promise.reject(new Error('boom!')); + }); - router.use(function sawError (err, req, res, next) { - res.send('saw ' + err.name + ': ' + err.message) - }) + router.use(function sawError(err, req, res, next) { + res.send('saw ' + err.name + ': ' + err.message); + }); - app.use(router) + app.use(router); - request(app) - .get('/') - .expect(200, 'saw Error: boom!', done) - }) + request(app).get('/').expect(200, 'saw Error: boom!', done); + }); it('should pass rejected promise without value', function (done) { - var app = express() - var router = new express.Router() + var app = express(); + var router = new express.Router(); - router.use(function createError (req, res, next) { - return Promise.reject() - }) + router.use(function createError(req, res, next) { + return Promise.reject(); + }); - router.use(function sawError (err, req, res, next) { - res.send('saw ' + err.name + ': ' + err.message) - }) + router.use(function sawError(err, req, res, next) { + res.send('saw ' + err.name + ': ' + err.message); + }); - app.use(router) + app.use(router); - request(app) - .get('/') - .expect(200, 'saw Error: Rejected promise', done) - }) + request(app).get('/').expect(200, 'saw Error: Rejected promise', done); + }); it('should ignore resolved promise', function (done) { - var app = express() - var router = new express.Router() + var app = express(); + var router = new express.Router(); - router.use(function createError (req, res, next) { - res.send('saw GET /foo') - return Promise.resolve('foo') - }) + router.use(function createError(req, res, next) { + res.send('saw GET /foo'); + return Promise.resolve('foo'); + }); router.use(function () { - done(new Error('Unexpected middleware invoke')) - }) + done(new Error('Unexpected middleware invoke')); + }); - app.use(router) + app.use(router); - request(app) - .get('/foo') - .expect(200, 'saw GET /foo', done) - }) + request(app).get('/foo').expect(200, 'saw GET /foo', done); + }); describe('error handling', function () { it('should pass rejected promise value', function (done) { - var app = express() - var router = new express.Router() + var app = express(); + var router = new express.Router(); - router.use(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + router.use(function createError(req, res, next) { + return Promise.reject(new Error('boom!')); + }); - router.use(function handleError (err, req, res, next) { - return Promise.reject(new Error('caught: ' + err.message)) - }) + router.use(function handleError(err, req, res, next) { + return Promise.reject(new Error('caught: ' + err.message)); + }); - router.use(function sawError (err, req, res, next) { - res.send('saw ' + err.name + ': ' + err.message) - }) + router.use(function sawError(err, req, res, next) { + res.send('saw ' + err.name + ': ' + err.message); + }); - app.use(router) + app.use(router); - request(app) - .get('/') - .expect(200, 'saw Error: caught: boom!', done) - }) + request(app).get('/').expect(200, 'saw Error: caught: boom!', done); + }); it('should pass rejected promise without value', function (done) { - var app = express() - var router = new express.Router() + var app = express(); + var router = new express.Router(); - router.use(function createError (req, res, next) { - return Promise.reject() - }) + router.use(function createError(req, res, next) { + return Promise.reject(); + }); - router.use(function handleError (err, req, res, next) { - return Promise.reject(new Error('caught: ' + err.message)) - }) + router.use(function handleError(err, req, res, next) { + return Promise.reject(new Error('caught: ' + err.message)); + }); - router.use(function sawError (err, req, res, next) { - res.send('saw ' + err.name + ': ' + err.message) - }) + router.use(function sawError(err, req, res, next) { + res.send('saw ' + err.name + ': ' + err.message); + }); - app.use(router) + app.use(router); request(app) - .get('/') - .expect(200, 'saw Error: caught: Rejected promise', done) - }) + .get('/') + .expect(200, 'saw Error: caught: Rejected promise', done); + }); it('should ignore resolved promise', function (done) { - var app = express() - var router = new express.Router() + var app = express(); + var router = new express.Router(); - router.use(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + router.use(function createError(req, res, next) { + return Promise.reject(new Error('boom!')); + }); - router.use(function handleError (err, req, res, next) { - res.send('saw ' + err.name + ': ' + err.message) - return Promise.resolve('foo') - }) + router.use(function handleError(err, req, res, next) { + res.send('saw ' + err.name + ': ' + err.message); + return Promise.resolve('foo'); + }); router.use(function () { - done(new Error('Unexpected middleware invoke')) - }) + done(new Error('Unexpected middleware invoke')); + }); - app.use(router) + app.use(router); - request(app) - .get('/foo') - .expect(200, 'saw Error: boom!', done) - }) - }) - }) + request(app).get('/foo').expect(200, 'saw Error: boom!', done); + }); + }); + }); - it('should allow rewriting of the url', function(done){ + it('should allow rewriting of the url', function (done) { var app = express(); - app.get('/account/edit', function(req, res, next){ + app.get('/account/edit', function (req, res, next) { req.user = { id: 12 }; // faux authenticated user req.url = '/user/' + req.user.id + '/edit'; next(); }); - app.get('/user/:id/edit', function(req, res){ + app.get('/user/:id/edit', function (req, res) { res.send('editing user ' + req.params.id); }); - request(app) - .get('/account/edit') - .expect('editing user 12', done); - }) + request(app).get('/account/edit').expect('editing user 12', done); + }); - it('should run in order added', function(done){ + it('should run in order added', function (done) { var app = express(); var path = []; @@ -1122,17 +1052,17 @@ describe('app.router', function(){ next(); }); - app.get('/user/:id', function(req, res, next){ + app.get('/user/:id', function (req, res, next) { path.push(1); next(); }); - app.use(function(req, res, next){ + app.use(function (req, res, next) { path.push(2); next(); }); - app.all('/user/:id', function(req, res, next){ + app.all('/user/:id', function (req, res, next) { path.push(3); next(); }); @@ -1142,28 +1072,29 @@ describe('app.router', function(){ next(); }); - app.use(function(req, res, next){ + app.use(function (req, res, next) { path.push(5); - res.end(path.join(',')) + res.end(path.join(',')); }); - request(app) - .get('/user/1') - .expect(200, '0,1,2,3,4,5', done); - }) + request(app).get('/user/1').expect(200, '0,1,2,3,4,5', done); + }); - it('should be chainable', function(){ + it('should be chainable', function () { var app = express(); - assert.strictEqual(app.get('/', function () {}), app) - }) + assert.strictEqual( + app.get('/', function () {}), + app, + ); + }); - it('should should not use disposed router/middleware', function(done){ + it('should should not use disposed router/middleware', function (done) { // more context: https://github.com/expressjs/express/issues/5743#issuecomment-2277148412 var app = express(); var router = new express.Router(); - router.use(function(req, res, next){ + router.use(function (req, res, next) { res.setHeader('old', 'foo'); next(); }); @@ -1172,47 +1103,47 @@ describe('app.router', function(){ return router.handle(req, res, next); }); - app.get('/', function(req, res, next){ + app.get('/', function (req, res, next) { res.send('yee'); next(); }); request(app) - .get('/') - .expect('old', 'foo') - .expect(function(res) { - if (typeof res.headers['new'] !== 'undefined') { - throw new Error('`new` header should not be present'); - } - }) - .expect(200, 'yee', function(err, res) { - if (err) return done(err); - - router = new express.Router(); - - router.use(function(req, res, next){ - res.setHeader('new', 'bar'); - next(); - }); - - request(app) .get('/') - .expect('new', 'bar') - .expect(function(res) { - if (typeof res.headers['old'] !== 'undefined') { - throw new Error('`old` header should not be present'); + .expect('old', 'foo') + .expect(function (res) { + if (typeof res.headers['new'] !== 'undefined') { + throw new Error('`new` header should not be present'); } }) - .expect(200, 'yee', done); - }); - }) -}) + .expect(200, 'yee', function (err, res) { + if (err) return done(err); + + router = new express.Router(); + + router.use(function (req, res, next) { + res.setHeader('new', 'bar'); + next(); + }); + + request(app) + .get('/') + .expect('new', 'bar') + .expect(function (res) { + if (typeof res.headers['old'] !== 'undefined') { + throw new Error('`old` header should not be present'); + } + }) + .expect(200, 'yee', done); + }); + }); +}); function supportsRegexp(source) { try { - new RegExp(source) - return true + new RegExp(source); + return true; } catch (e) { - return false + return false; } } diff --git a/test/app.routes.error.js b/test/app.routes.error.js index efc0108b0f2..befae28e438 100644 --- a/test/app.routes.error.js +++ b/test/app.routes.error.js @@ -1,28 +1,28 @@ -'use strict' +'use strict'; -var assert = require('assert') -var express = require('../') - , request = require('supertest'); +var assert = require('assert'); +var express = require('../'), + request = require('supertest'); -describe('app', function(){ - describe('.VERB()', function(){ - it('should not get invoked without error handler on error', function(done) { +describe('app', function () { + describe('.VERB()', function () { + it('should not get invoked without error handler on error', function (done) { var app = express(); - app.use(function(req, res, next){ - next(new Error('boom!')) + app.use(function (req, res, next) { + next(new Error('boom!')); }); - app.get('/bar', function(req, res){ + app.get('/bar', function (req, res) { res.send('hello, world!'); }); request(app) - .post('/bar') - .expect(500, /Error: boom!/, done); + .post('/bar') + .expect(500, /Error: boom!/, done); }); - it('should only call an error handling routing callback when an error is propagated', function(done){ + it('should only call an error handling routing callback when an error is propagated', function (done) { var app = express(); var a = false; @@ -30,33 +30,39 @@ describe('app', function(){ var c = false; var d = false; - app.get('/', function(req, res, next){ - next(new Error('fabricated error')); - }, function(req, res, next) { - a = true; - next(); - }, function(err, req, res, next){ - b = true; - assert.strictEqual(err.message, 'fabricated error') - next(err); - }, function(err, req, res, next){ - c = true; - assert.strictEqual(err.message, 'fabricated error') - next(); - }, function(err, req, res, next){ - d = true; - next(); - }, function(req, res){ - assert.ok(!a) - assert.ok(b) - assert.ok(c) - assert.ok(!d) - res.sendStatus(204); - }); + app.get( + '/', + function (req, res, next) { + next(new Error('fabricated error')); + }, + function (req, res, next) { + a = true; + next(); + }, + function (err, req, res, next) { + b = true; + assert.strictEqual(err.message, 'fabricated error'); + next(err); + }, + function (err, req, res, next) { + c = true; + assert.strictEqual(err.message, 'fabricated error'); + next(); + }, + function (err, req, res, next) { + d = true; + next(); + }, + function (req, res) { + assert.ok(!a); + assert.ok(b); + assert.ok(c); + assert.ok(!d); + res.sendStatus(204); + }, + ); - request(app) - .get('/') - .expect(204, done); - }) - }) -}) + request(app).get('/').expect(204, done); + }); + }); +}); diff --git a/test/app.use.js b/test/app.use.js index a88a2f2c8e9..1bff9e0c221 100644 --- a/test/app.use.js +++ b/test/app.use.js @@ -1,93 +1,85 @@ -'use strict' +'use strict'; var after = require('after'); -var assert = require('assert') +var assert = require('assert'); var express = require('..'); var request = require('supertest'); -describe('app', function(){ - it('should emit "mount" when mounted', function(done){ - var blog = express() - , app = express(); +describe('app', function () { + it('should emit "mount" when mounted', function (done) { + var blog = express(), + app = express(); - blog.on('mount', function(arg){ - assert.strictEqual(arg, app) + blog.on('mount', function (arg) { + assert.strictEqual(arg, app); done(); }); app.use(blog); - }) + }); - describe('.use(app)', function(){ - it('should mount the app', function(done){ - var blog = express() - , app = express(); + describe('.use(app)', function () { + it('should mount the app', function (done) { + var blog = express(), + app = express(); - blog.get('/blog', function(req, res){ + blog.get('/blog', function (req, res) { res.end('blog'); }); app.use(blog); - request(app) - .get('/blog') - .expect('blog', done); - }) + request(app).get('/blog').expect('blog', done); + }); - it('should support mount-points', function(done){ - var blog = express() - , forum = express() - , app = express(); - var cb = after(2, done) + it('should support mount-points', function (done) { + var blog = express(), + forum = express(), + app = express(); + var cb = after(2, done); - blog.get('/', function(req, res){ + blog.get('/', function (req, res) { res.end('blog'); }); - forum.get('/', function(req, res){ + forum.get('/', function (req, res) { res.end('forum'); }); app.use('/blog', blog); app.use('/forum', forum); - request(app) - .get('/blog') - .expect(200, 'blog', cb) + request(app).get('/blog').expect(200, 'blog', cb); - request(app) - .get('/forum') - .expect(200, 'forum', cb) - }) + request(app).get('/forum').expect(200, 'forum', cb); + }); - it('should set the child\'s .parent', function(){ - var blog = express() - , app = express(); + it("should set the child's .parent", function () { + var blog = express(), + app = express(); app.use('/blog', blog); - assert.strictEqual(blog.parent, app) - }) + assert.strictEqual(blog.parent, app); + }); - it('should support dynamic routes', function(done){ - var blog = express() - , app = express(); + it('should support dynamic routes', function (done) { + var blog = express(), + app = express(); - blog.get('/', function(req, res){ + blog.get('/', function (req, res) { res.end('success'); }); app.use('/post/:article', blog); - request(app) - .get('/post/once-upon-a-time') - .expect('success', done); - }) + request(app).get('/post/once-upon-a-time').expect('success', done); + }); - it('should support mounted app anywhere', function(done){ + it('should support mounted app anywhere', function (done) { var cb = after(3, done); - var blog = express() - , other = express() - , app = express(); + var blog = express(), + other = express(), + app = express(); function fn1(req, res, next) { res.setHeader('x-fn-1', 'hit'); @@ -99,30 +91,30 @@ describe('app', function(){ next(); } - blog.get('/', function(req, res){ + blog.get('/', function (req, res) { res.end('success'); }); blog.once('mount', function (parent) { - assert.strictEqual(parent, app) + assert.strictEqual(parent, app); cb(); }); other.once('mount', function (parent) { - assert.strictEqual(parent, app) + assert.strictEqual(parent, app); cb(); }); app.use('/post/:article', fn1, other, fn2, blog); request(app) - .get('/post/once-upon-a-time') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('success', cb); - }) - }) - - describe('.use(middleware)', function(){ + .get('/post/once-upon-a-time') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('success', cb); + }); + }); + + describe('.use(middleware)', function () { it('should accept multiple arguments', function (done) { var app = express(); @@ -142,12 +134,12 @@ describe('app', function(){ }); request(app) - .get('/') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); - }) + .get('/') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done); + }); it('should invoke middleware for all requests', function (done) { var app = express(); @@ -157,18 +149,12 @@ describe('app', function(){ res.send('saw ' + req.method + ' ' + req.url); }); - request(app) - .get('/') - .expect(200, 'saw GET /', cb); + request(app).get('/').expect(200, 'saw GET /', cb); - request(app) - .options('/') - .expect(200, 'saw OPTIONS /', cb); + request(app).options('/').expect(200, 'saw OPTIONS /', cb); - request(app) - .post('/foo') - .expect(200, 'saw POST /foo', cb); - }) + request(app).post('/foo').expect(200, 'saw POST /foo', cb); + }); it('should accept array of middleware', function (done) { var app = express(); @@ -191,12 +177,12 @@ describe('app', function(){ app.use([fn1, fn2, fn3]); request(app) - .get('/') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); - }) + .get('/') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done); + }); it('should accept multiple arrays of middleware', function (done) { var app = express(); @@ -219,12 +205,12 @@ describe('app', function(){ app.use([fn1, fn2], [fn3]); request(app) - .get('/') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); - }) + .get('/') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done); + }); it('should accept nested arrays of middleware', function (done) { var app = express(); @@ -247,39 +233,49 @@ describe('app', function(){ app.use([[fn1], fn2], [fn3]); request(app) - .get('/') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); - }) - }) - - describe('.use(path, middleware)', function(){ + .get('/') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done); + }); + }); + + describe('.use(path, middleware)', function () { it('should require middleware', function () { - var app = express() - assert.throws(function () { app.use('/') }, 'TypeError: app.use() requires a middleware function') - }) + var app = express(); + assert.throws(function () { + app.use('/'); + }, 'TypeError: app.use() requires a middleware function'); + }); it('should reject string as middleware', function () { - var app = express() - assert.throws(function () { app.use('/', 'foo') }, /argument handler must be a function/) - }) + var app = express(); + assert.throws(function () { + app.use('/', 'foo'); + }, /argument handler must be a function/); + }); it('should reject number as middleware', function () { - var app = express() - assert.throws(function () { app.use('/', 42) }, /argument handler must be a function/) - }) + var app = express(); + assert.throws(function () { + app.use('/', 42); + }, /argument handler must be a function/); + }); it('should reject null as middleware', function () { - var app = express() - assert.throws(function () { app.use('/', null) }, /argument handler must be a function/) - }) + var app = express(); + assert.throws(function () { + app.use('/', null); + }, /argument handler must be a function/); + }); it('should reject Date as middleware', function () { - var app = express() - assert.throws(function () { app.use('/', new Date()) }, /argument handler must be a function/) - }) + var app = express(); + assert.throws(function () { + app.use('/', new Date()); + }, /argument handler must be a function/); + }); it('should strip path from req.url', function (done) { var app = express(); @@ -288,10 +284,8 @@ describe('app', function(){ res.send('saw ' + req.method + ' ' + req.url); }); - request(app) - .get('/foo/bar') - .expect(200, 'saw GET /bar', done); - }) + request(app).get('/foo/bar').expect(200, 'saw GET /bar', done); + }); it('should accept multiple arguments', function (done) { var app = express(); @@ -312,12 +306,12 @@ describe('app', function(){ }); request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); - }) + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done); + }); it('should invoke middleware for all requests starting with path', function (done) { var app = express(); @@ -327,18 +321,12 @@ describe('app', function(){ res.send('saw ' + req.method + ' ' + req.url); }); - request(app) - .get('/') - .expect(404, cb); + request(app).get('/').expect(404, cb); - request(app) - .post('/foo') - .expect(200, 'saw POST /', cb); + request(app).post('/foo').expect(200, 'saw POST /', cb); - request(app) - .post('/foo/bar') - .expect(200, 'saw POST /bar', cb); - }) + request(app).post('/foo/bar').expect(200, 'saw POST /bar', cb); + }); it('should work if path has trailing slash', function (done) { var app = express(); @@ -348,18 +336,12 @@ describe('app', function(){ res.send('saw ' + req.method + ' ' + req.url); }); - request(app) - .get('/') - .expect(404, cb); + request(app).get('/').expect(404, cb); - request(app) - .post('/foo') - .expect(200, 'saw POST /', cb); + request(app).post('/foo').expect(200, 'saw POST /', cb); - request(app) - .post('/foo/bar') - .expect(200, 'saw POST /bar', cb); - }) + request(app).post('/foo/bar').expect(200, 'saw POST /bar', cb); + }); it('should accept array of middleware', function (done) { var app = express(); @@ -382,12 +364,12 @@ describe('app', function(){ app.use('/foo', [fn1, fn2, fn3]); request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); - }) + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done); + }); it('should accept multiple arrays of middleware', function (done) { var app = express(); @@ -410,12 +392,12 @@ describe('app', function(){ app.use('/foo', [fn1, fn2], [fn3]); request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); - }) + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done); + }); it('should accept nested arrays of middleware', function (done) { var app = express(); @@ -438,33 +420,29 @@ describe('app', function(){ app.use('/foo', [fn1, [fn2]], [fn3]); request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); - }) + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done); + }); it('should support array of paths', function (done) { var app = express(); var cb = after(3, done); app.use(['/foo/', '/bar'], function (req, res) { - res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl); + res.send( + 'saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl, + ); }); - request(app) - .get('/') - .expect(404, cb); + request(app).get('/').expect(404, cb); - request(app) - .get('/foo') - .expect(200, 'saw GET / through /foo', cb); + request(app).get('/foo').expect(200, 'saw GET / through /foo', cb); - request(app) - .get('/bar') - .expect(200, 'saw GET / through /bar', cb); - }) + request(app).get('/bar').expect(200, 'saw GET / through /bar', cb); + }); it('should support array of paths with middleware array', function (done) { var app = express(); @@ -482,61 +460,59 @@ describe('app', function(){ function fn3(req, res, next) { res.setHeader('x-fn-3', 'hit'); - res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl); + res.send( + 'saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl, + ); } app.use(['/foo/', '/bar'], [[fn1], fn2], [fn3]); request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, 'saw GET / through /foo', cb); + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, 'saw GET / through /foo', cb); request(app) - .get('/bar') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, 'saw GET / through /bar', cb); - }) + .get('/bar') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, 'saw GET / through /bar', cb); + }); it('should support regexp path', function (done) { var app = express(); var cb = after(4, done); app.use(/^\/[a-z]oo/, function (req, res) { - res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl); + res.send( + 'saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl, + ); }); - request(app) - .get('/') - .expect(404, cb); + request(app).get('/').expect(404, cb); - request(app) - .get('/foo') - .expect(200, 'saw GET / through /foo', cb); + request(app).get('/foo').expect(200, 'saw GET / through /foo', cb); request(app) - .get('/zoo/bear') - .expect(200, 'saw GET /bear through /zoo/bear', cb); + .get('/zoo/bear') + .expect(200, 'saw GET /bear through /zoo/bear', cb); - request(app) - .get('/get/zoo') - .expect(404, cb); - }) + request(app).get('/get/zoo').expect(404, cb); + }); it('should support empty string path', function (done) { var app = express(); app.use('', function (req, res) { - res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl); + res.send( + 'saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl, + ); }); - request(app) - .get('/') - .expect(200, 'saw GET / through /', done); - }) - }) -}) + request(app).get('/').expect(200, 'saw GET / through /', done); + }); + }); +}); diff --git a/test/config.js b/test/config.js index b04367fdbf8..0b082b19e4d 100644 --- a/test/config.js +++ b/test/config.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; var assert = require('assert'); var express = require('..'); @@ -9,87 +9,87 @@ describe('config', function () { var app = express(); app.set('foo', 'bar'); assert.equal(app.get('foo'), 'bar'); - }) + }); it('should set prototype values', function () { - var app = express() - app.set('hasOwnProperty', 42) - assert.strictEqual(app.get('hasOwnProperty'), 42) - }) + var app = express(); + app.set('hasOwnProperty', 42); + assert.strictEqual(app.get('hasOwnProperty'), 42); + }); it('should return the app', function () { var app = express(); assert.equal(app.set('foo', 'bar'), app); - }) + }); it('should return the app when undefined', function () { var app = express(); assert.equal(app.set('foo', undefined), app); - }) + }); it('should return set value', function () { - var app = express() - app.set('foo', 'bar') - assert.strictEqual(app.set('foo'), 'bar') - }) + var app = express(); + app.set('foo', 'bar'); + assert.strictEqual(app.set('foo'), 'bar'); + }); it('should return undefined for prototype values', function () { - var app = express() - assert.strictEqual(app.set('hasOwnProperty'), undefined) - }) + var app = express(); + assert.strictEqual(app.set('hasOwnProperty'), undefined); + }); - describe('"etag"', function(){ - it('should throw on bad value', function(){ + describe('"etag"', function () { + it('should throw on bad value', function () { var app = express(); assert.throws(app.set.bind(app, 'etag', 42), /unknown value/); - }) - - it('should set "etag fn"', function(){ - var app = express() - var fn = function(){} - app.set('etag', fn) - assert.equal(app.get('etag fn'), fn) - }) - }) - - describe('"trust proxy"', function(){ - it('should set "trust proxy fn"', function(){ - var app = express() - var fn = function(){} - app.set('trust proxy', fn) - assert.equal(app.get('trust proxy fn'), fn) - }) - }) - }) - - describe('.get()', function(){ - it('should return undefined when unset', function(){ + }); + + it('should set "etag fn"', function () { + var app = express(); + var fn = function () {}; + app.set('etag', fn); + assert.equal(app.get('etag fn'), fn); + }); + }); + + describe('"trust proxy"', function () { + it('should set "trust proxy fn"', function () { + var app = express(); + var fn = function () {}; + app.set('trust proxy', fn); + assert.equal(app.get('trust proxy fn'), fn); + }); + }); + }); + + describe('.get()', function () { + it('should return undefined when unset', function () { var app = express(); assert.strictEqual(app.get('foo'), undefined); - }) + }); it('should return undefined for prototype values', function () { - var app = express() - assert.strictEqual(app.get('hasOwnProperty'), undefined) - }) + var app = express(); + assert.strictEqual(app.get('hasOwnProperty'), undefined); + }); - it('should otherwise return the value', function(){ + it('should otherwise return the value', function () { var app = express(); app.set('foo', 'bar'); assert.equal(app.get('foo'), 'bar'); - }) + }); - describe('when mounted', function(){ - it('should default to the parent app', function(){ + describe('when mounted', function () { + it('should default to the parent app', function () { var app = express(); var blog = express(); app.set('title', 'Express'); app.use(blog); assert.equal(blog.get('title'), 'Express'); - }) + }); - it('should given precedence to the child', function(){ + it('should given precedence to the child', function () { var app = express(); var blog = express(); @@ -98,13 +98,15 @@ describe('config', function () { blog.set('title', 'Some Blog'); assert.equal(blog.get('title'), 'Some Blog'); - }) + }); it('should inherit "trust proxy" setting', function () { var app = express(); var blog = express(); - function fn() { return false } + function fn() { + return false; + } app.set('trust proxy', fn); assert.equal(app.get('trust proxy'), fn); @@ -114,14 +116,18 @@ describe('config', function () { assert.equal(blog.get('trust proxy'), fn); assert.equal(blog.get('trust proxy fn'), fn); - }) + }); it('should prefer child "trust proxy" setting', function () { var app = express(); var blog = express(); - function fn1() { return false } - function fn2() { return true } + function fn1() { + return false; + } + function fn2() { + return true; + } app.set('trust proxy', fn1); assert.equal(app.get('trust proxy'), fn1); @@ -137,71 +143,71 @@ describe('config', function () { assert.equal(app.get('trust proxy fn'), fn1); assert.equal(blog.get('trust proxy'), fn2); assert.equal(blog.get('trust proxy fn'), fn2); - }) - }) - }) + }); + }); + }); - describe('.enable()', function(){ - it('should set the value to true', function(){ + describe('.enable()', function () { + it('should set the value to true', function () { var app = express(); assert.equal(app.enable('tobi'), app); assert.strictEqual(app.get('tobi'), true); - }) + }); it('should set prototype values', function () { - var app = express() - app.enable('hasOwnProperty') - assert.strictEqual(app.get('hasOwnProperty'), true) - }) - }) + var app = express(); + app.enable('hasOwnProperty'); + assert.strictEqual(app.get('hasOwnProperty'), true); + }); + }); - describe('.disable()', function(){ - it('should set the value to false', function(){ + describe('.disable()', function () { + it('should set the value to false', function () { var app = express(); assert.equal(app.disable('tobi'), app); assert.strictEqual(app.get('tobi'), false); - }) + }); it('should set prototype values', function () { - var app = express() - app.disable('hasOwnProperty') - assert.strictEqual(app.get('hasOwnProperty'), false) - }) - }) + var app = express(); + app.disable('hasOwnProperty'); + assert.strictEqual(app.get('hasOwnProperty'), false); + }); + }); - describe('.enabled()', function(){ - it('should default to false', function(){ + describe('.enabled()', function () { + it('should default to false', function () { var app = express(); assert.strictEqual(app.enabled('foo'), false); - }) + }); - it('should return true when set', function(){ + it('should return true when set', function () { var app = express(); app.set('foo', 'bar'); assert.strictEqual(app.enabled('foo'), true); - }) + }); it('should default to false for prototype values', function () { - var app = express() - assert.strictEqual(app.enabled('hasOwnProperty'), false) - }) - }) + var app = express(); + assert.strictEqual(app.enabled('hasOwnProperty'), false); + }); + }); - describe('.disabled()', function(){ - it('should default to true', function(){ + describe('.disabled()', function () { + it('should default to true', function () { var app = express(); assert.strictEqual(app.disabled('foo'), true); - }) + }); - it('should return false when set', function(){ + it('should return false when set', function () { var app = express(); app.set('foo', 'bar'); assert.strictEqual(app.disabled('foo'), false); - }) + }); it('should default to true for prototype values', function () { - var app = express() - assert.strictEqual(app.disabled('hasOwnProperty'), true) - }) - }) -}) + var app = express(); + assert.strictEqual(app.disabled('hasOwnProperty'), true); + }); + }); +}); diff --git a/test/exports.js b/test/exports.js index dc635d1dbcb..e08475281cc 100644 --- a/test/exports.js +++ b/test/exports.js @@ -1,82 +1,84 @@ -'use strict' +'use strict'; -var assert = require('assert') +var assert = require('assert'); var express = require('../'); var request = require('supertest'); -describe('exports', function(){ - it('should expose Router', function(){ - assert.strictEqual(typeof express.Router, 'function') - }) +describe('exports', function () { + it('should expose Router', function () { + assert.strictEqual(typeof express.Router, 'function'); + }); it('should expose json middleware', function () { - assert.equal(typeof express.json, 'function') - assert.equal(express.json.length, 1) - }) + assert.equal(typeof express.json, 'function'); + assert.equal(express.json.length, 1); + }); it('should expose raw middleware', function () { - assert.equal(typeof express.raw, 'function') - assert.equal(express.raw.length, 1) - }) + assert.equal(typeof express.raw, 'function'); + assert.equal(express.raw.length, 1); + }); it('should expose static middleware', function () { - assert.equal(typeof express.static, 'function') - assert.equal(express.static.length, 2) - }) + assert.equal(typeof express.static, 'function'); + assert.equal(express.static.length, 2); + }); it('should expose text middleware', function () { - assert.equal(typeof express.text, 'function') - assert.equal(express.text.length, 1) - }) + assert.equal(typeof express.text, 'function'); + assert.equal(express.text.length, 1); + }); it('should expose urlencoded middleware', function () { - assert.equal(typeof express.urlencoded, 'function') - assert.equal(express.urlencoded.length, 1) - }) - - it('should expose the application prototype', function(){ - assert.strictEqual(typeof express.application, 'object') - assert.strictEqual(typeof express.application.set, 'function') - }) - - it('should expose the request prototype', function(){ - assert.strictEqual(typeof express.request, 'object') - assert.strictEqual(typeof express.request.accepts, 'function') - }) - - it('should expose the response prototype', function(){ - assert.strictEqual(typeof express.response, 'object') - assert.strictEqual(typeof express.response.send, 'function') - }) - - it('should permit modifying the .application prototype', function(){ - express.application.foo = function(){ return 'bar'; }; - assert.strictEqual(express().foo(), 'bar') - }) - - it('should permit modifying the .request prototype', function(done){ - express.request.foo = function(){ return 'bar'; }; + assert.equal(typeof express.urlencoded, 'function'); + assert.equal(express.urlencoded.length, 1); + }); + + it('should expose the application prototype', function () { + assert.strictEqual(typeof express.application, 'object'); + assert.strictEqual(typeof express.application.set, 'function'); + }); + + it('should expose the request prototype', function () { + assert.strictEqual(typeof express.request, 'object'); + assert.strictEqual(typeof express.request.accepts, 'function'); + }); + + it('should expose the response prototype', function () { + assert.strictEqual(typeof express.response, 'object'); + assert.strictEqual(typeof express.response.send, 'function'); + }); + + it('should permit modifying the .application prototype', function () { + express.application.foo = function () { + return 'bar'; + }; + assert.strictEqual(express().foo(), 'bar'); + }); + + it('should permit modifying the .request prototype', function (done) { + express.request.foo = function () { + return 'bar'; + }; var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.foo()); }); - request(app) - .get('/') - .expect('bar', done); - }) + request(app).get('/').expect('bar', done); + }); - it('should permit modifying the .response prototype', function(done){ - express.response.foo = function(){ this.send('bar'); }; + it('should permit modifying the .response prototype', function (done) { + express.response.foo = function () { + this.send('bar'); + }; var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.foo(); }); - request(app) - .get('/') - .expect('bar', done); - }) -}) + request(app).get('/').expect('bar', done); + }); +}); diff --git a/test/express.json.js b/test/express.json.js index 859347e1dcb..f9be51d9cb8 100644 --- a/test/express.json.js +++ b/test/express.json.js @@ -1,14 +1,13 @@ -'use strict' +'use strict'; -var assert = require('assert') -var asyncHooks = tryRequire('async_hooks') -var Buffer = require('safe-buffer').Buffer -var express = require('..') -var request = require('supertest') +var assert = require('assert'); +var asyncHooks = tryRequire('async_hooks'); +var Buffer = require('safe-buffer').Buffer; +var express = require('..'); +var request = require('supertest'); -var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function' - ? describe - : describe.skip +var describeAsyncHooks = + typeof asyncHooks.AsyncLocalStorage === 'function' ? describe : describe.skip; describe('express.json()', function () { it('should parse JSON', function (done) { @@ -16,32 +15,32 @@ describe('express.json()', function () { .post('/') .set('Content-Type', 'application/json') .send('{"user":"tobi"}') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should handle Content-Length: 0', function (done) { request(createApp()) .post('/') .set('Content-Type', 'application/json') .set('Content-Length', '0') - .expect(200, '{}', done) - }) + .expect(200, '{}', done); + }); it('should handle empty message-body', function (done) { request(createApp()) .post('/') .set('Content-Type', 'application/json') .set('Transfer-Encoding', 'chunked') - .expect(200, '{}', done) - }) + .expect(200, '{}', done); + }); it('should handle no message-body', function (done) { request(createApp()) .post('/') .set('Content-Type', 'application/json') .unset('Transfer-Encoding') - .expect(200, '{}', done) - }) + .expect(200, '{}', done); + }); // The old node error message modification in body parser is catching this it('should 400 when only whitespace', function (done) { @@ -49,67 +48,67 @@ describe('express.json()', function () { .post('/') .set('Content-Type', 'application/json') .send(' \n') - .expect(400, '[entity.parse.failed] ' + parseError(' \n'), done) - }) + .expect(400, '[entity.parse.failed] ' + parseError(' \n'), done); + }); it('should 400 when invalid content-length', function (done) { - var app = express() + var app = express(); app.use(function (req, res, next) { - req.headers['content-length'] = '20' // bad length - next() - }) + req.headers['content-length'] = '20'; // bad length + next(); + }); - app.use(express.json()) + app.use(express.json()); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); request(app) .post('/') .set('Content-Type', 'application/json') .send('{"str":') - .expect(400, /content length/, done) - }) + .expect(400, /content length/, done); + }); it('should handle duplicated middleware', function (done) { - var app = express() + var app = express(); - app.use(express.json()) - app.use(express.json()) + app.use(express.json()); + app.use(express.json()); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); request(app) .post('/') .set('Content-Type', 'application/json') .send('{"user":"tobi"}') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); describe('when JSON is invalid', function () { before(function () { - this.app = createApp() - }) + this.app = createApp(); + }); it('should 400 for bad token', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/json') .send('{:') - .expect(400, '[entity.parse.failed] ' + parseError('{:'), done) - }) + .expect(400, '[entity.parse.failed] ' + parseError('{:'), done); + }); it('should 400 for incomplete', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/json') .send('{"user"') - .expect(400, '[entity.parse.failed] ' + parseError('{"user"'), done) - }) + .expect(400, '[entity.parse.failed] ' + parseError('{"user"'), done); + }); it('should include original body on error object', function (done) { request(this.app) @@ -117,172 +116,209 @@ describe('express.json()', function () { .set('Content-Type', 'application/json') .set('X-Error-Property', 'body') .send(' {"user"') - .expect(400, ' {"user"', done) - }) - }) + .expect(400, ' {"user"', done); + }); + }); describe('with limit option', function () { it('should 413 when over limit with Content-Length', function (done) { - var buf = Buffer.alloc(1024, '.') + var buf = Buffer.alloc(1024, '.'); request(createApp({ limit: '1kb' })) .post('/') .set('Content-Type', 'application/json') .set('Content-Length', '1034') .send(JSON.stringify({ str: buf.toString() })) - .expect(413, '[entity.too.large] request entity too large', done) - }) + .expect(413, '[entity.too.large] request entity too large', done); + }); it('should 413 when over limit with chunked encoding', function (done) { - var app = createApp({ limit: '1kb' }) - var buf = Buffer.alloc(1024, '.') - var test = request(app).post('/') - test.set('Content-Type', 'application/json') - test.set('Transfer-Encoding', 'chunked') - test.write('{"str":') - test.write('"' + buf.toString() + '"}') - test.expect(413, done) - }) + var app = createApp({ limit: '1kb' }); + var buf = Buffer.alloc(1024, '.'); + var test = request(app).post('/'); + test.set('Content-Type', 'application/json'); + test.set('Transfer-Encoding', 'chunked'); + test.write('{"str":'); + test.write('"' + buf.toString() + '"}'); + test.expect(413, done); + }); it('should 413 when inflated body over limit', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a040000', 'hex')) - test.expect(413, done) - }) + var app = createApp({ limit: '1kb' }); + var test = request(app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a040000', + 'hex', + ), + ); + test.expect(413, done); + }); it('should accept number of bytes', function (done) { - var buf = Buffer.alloc(1024, '.') + var buf = Buffer.alloc(1024, '.'); request(createApp({ limit: 1024 })) .post('/') .set('Content-Type', 'application/json') .send(JSON.stringify({ str: buf.toString() })) - .expect(413, done) - }) + .expect(413, done); + }); it('should not change when options altered', function (done) { - var buf = Buffer.alloc(1024, '.') - var options = { limit: '1kb' } - var app = createApp(options) + var buf = Buffer.alloc(1024, '.'); + var options = { limit: '1kb' }; + var app = createApp(options); - options.limit = '100kb' + options.limit = '100kb'; request(app) .post('/') .set('Content-Type', 'application/json') .send(JSON.stringify({ str: buf.toString() })) - .expect(413, done) - }) + .expect(413, done); + }); it('should not hang response', function (done) { - var buf = Buffer.alloc(10240, '.') - var app = createApp({ limit: '8kb' }) - var test = request(app).post('/') - test.set('Content-Type', 'application/json') - test.write(buf) - test.write(buf) - test.write(buf) - test.expect(413, done) - }) + var buf = Buffer.alloc(10240, '.'); + var app = createApp({ limit: '8kb' }); + var test = request(app).post('/'); + test.set('Content-Type', 'application/json'); + test.write(buf); + test.write(buf); + test.write(buf); + test.expect(413, done); + }); it('should not error when inflating', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a0400', 'hex')) - test.expect(413, done) - }) - }) + var app = createApp({ limit: '1kb' }); + var test = request(app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a0400', + 'hex', + ), + ); + test.expect(413, done); + }); + }); describe('with inflate option', function () { describe('when false', function () { before(function () { - this.app = createApp({ inflate: false }) - }) + this.app = createApp({ inflate: false }); + }); it('should not accept content-encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) - test.expect(415, '[encoding.unsupported] content encoding unsupported', done) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', + 'hex', + ), + ); + test.expect( + 415, + '[encoding.unsupported] content encoding unsupported', + done, + ); + }); + }); describe('when true', function () { before(function () { - this.app = createApp({ inflate: true }) - }) + this.app = createApp({ inflate: true }); + }); it('should accept content-encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', + 'hex', + ), + ); + test.expect(200, '{"name":"论"}', done); + }); + }); + }); describe('with strict option', function () { describe('when undefined', function () { before(function () { - this.app = createApp() - }) + this.app = createApp(); + }); it('should 400 on primitives', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/json') .send('true') - .expect(400, '[entity.parse.failed] ' + parseError('#rue').replace(/#/g, 't'), done) - }) - }) + .expect( + 400, + '[entity.parse.failed] ' + parseError('#rue').replace(/#/g, 't'), + done, + ); + }); + }); describe('when false', function () { before(function () { - this.app = createApp({ strict: false }) - }) + this.app = createApp({ strict: false }); + }); it('should parse primitives', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/json') .send('true') - .expect(200, 'true', done) - }) - }) + .expect(200, 'true', done); + }); + }); describe('when true', function () { before(function () { - this.app = createApp({ strict: true }) - }) + this.app = createApp({ strict: true }); + }); it('should not parse primitives', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/json') .send('true') - .expect(400, '[entity.parse.failed] ' + parseError('#rue').replace(/#/g, 't'), done) - }) + .expect( + 400, + '[entity.parse.failed] ' + parseError('#rue').replace(/#/g, 't'), + done, + ); + }); it('should not parse primitives with leading whitespaces', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/json') .send(' true') - .expect(400, '[entity.parse.failed] ' + parseError(' #rue').replace(/#/g, 't'), done) - }) + .expect( + 400, + '[entity.parse.failed] ' + + parseError(' #rue').replace(/#/g, 't'), + done, + ); + }); it('should allow leading whitespaces in JSON', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/json') .send(' { "user": "tobi" }') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should include correct message in stack trace', function (done) { request(this.app) @@ -292,256 +328,265 @@ describe('express.json()', function () { .send('true') .expect(400) .expect(shouldContainInBody(parseError('#rue').replace(/#/g, 't'))) - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); describe('with type option', function () { describe('when "application/vnd.api+json"', function () { before(function () { - this.app = createApp({ type: 'application/vnd.api+json' }) - }) + this.app = createApp({ type: 'application/vnd.api+json' }); + }); it('should parse JSON for custom type', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/vnd.api+json') .send('{"user":"tobi"}') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should ignore standard type', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/json') .send('{"user":"tobi"}') - .expect(200, '', done) - }) - }) + .expect(200, '', done); + }); + }); describe('when ["application/json", "application/vnd.api+json"]', function () { before(function () { this.app = createApp({ - type: ['application/json', 'application/vnd.api+json'] - }) - }) + type: ['application/json', 'application/vnd.api+json'], + }); + }); it('should parse JSON for "application/json"', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/json') .send('{"user":"tobi"}') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should parse JSON for "application/vnd.api+json"', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/vnd.api+json') .send('{"user":"tobi"}') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should ignore "application/x-json"', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-json') .send('{"user":"tobi"}') - .expect(200, '', done) - }) - }) + .expect(200, '', done); + }); + }); describe('when a function', function () { it('should parse when truthy value returned', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - return req.headers['content-type'] === 'application/vnd.api+json' + function accept(req) { + return req.headers['content-type'] === 'application/vnd.api+json'; } request(app) .post('/') .set('Content-Type', 'application/vnd.api+json') .send('{"user":"tobi"}') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should work without content-type', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - return true + function accept(req) { + return true; } - var test = request(app).post('/') - test.write('{"user":"tobi"}') - test.expect(200, '{"user":"tobi"}', done) - }) + var test = request(app).post('/'); + test.write('{"user":"tobi"}'); + test.expect(200, '{"user":"tobi"}', done); + }); it('should not invoke without a body', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - throw new Error('oops!') + function accept(req) { + throw new Error('oops!'); } - request(app) - .get('/') - .expect(404, done) - }) - }) - }) + request(app).get('/').expect(404, done); + }); + }); + }); describe('with verify option', function () { it('should assert value if function', function () { - assert.throws(createApp.bind(null, { verify: 'lol' }), - /TypeError: option verify must be function/) - }) + assert.throws( + createApp.bind(null, { verify: 'lol' }), + /TypeError: option verify must be function/, + ); + }); it('should error from verify', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x5b) throw new Error('no arrays') - } - }) + if (buf[0] === 0x5b) throw new Error('no arrays'); + }, + }); request(app) .post('/') .set('Content-Type', 'application/json') .send('["tobi"]') - .expect(403, '[entity.verify.failed] no arrays', done) - }) + .expect(403, '[entity.verify.failed] no arrays', done); + }); it('should allow custom codes', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] !== 0x5b) return - var err = new Error('no arrays') - err.status = 400 - throw err - } - }) + if (buf[0] !== 0x5b) return; + var err = new Error('no arrays'); + err.status = 400; + throw err; + }, + }); request(app) .post('/') .set('Content-Type', 'application/json') .send('["tobi"]') - .expect(400, '[entity.verify.failed] no arrays', done) - }) + .expect(400, '[entity.verify.failed] no arrays', done); + }); it('should allow custom type', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] !== 0x5b) return - var err = new Error('no arrays') - err.type = 'foo.bar' - throw err - } - }) + if (buf[0] !== 0x5b) return; + var err = new Error('no arrays'); + err.type = 'foo.bar'; + throw err; + }, + }); request(app) .post('/') .set('Content-Type', 'application/json') .send('["tobi"]') - .expect(403, '[foo.bar] no arrays', done) - }) + .expect(403, '[foo.bar] no arrays', done); + }); it('should include original body on error object', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x5b) throw new Error('no arrays') - } - }) + if (buf[0] === 0x5b) throw new Error('no arrays'); + }, + }); request(app) .post('/') .set('Content-Type', 'application/json') .set('X-Error-Property', 'body') .send('["tobi"]') - .expect(403, '["tobi"]', done) - }) + .expect(403, '["tobi"]', done); + }); it('should allow pass-through', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x5b) throw new Error('no arrays') - } - }) + if (buf[0] === 0x5b) throw new Error('no arrays'); + }, + }); request(app) .post('/') .set('Content-Type', 'application/json') .send('{"user":"tobi"}') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should work with different charsets', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x5b) throw new Error('no arrays') - } - }) - - var test = request(app).post('/') - test.set('Content-Type', 'application/json; charset=utf-16') - test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + if (buf[0] === 0x5b) throw new Error('no arrays'); + }, + }); + + var test = request(app).post('/'); + test.set('Content-Type', 'application/json; charset=utf-16'); + test.write( + Buffer.from( + 'feff007b0022006e0061006d00650022003a00228bba0022007d', + 'hex', + ), + ); + test.expect(200, '{"name":"论"}', done); + }); it('should 415 on unknown charset prior to verify', function (done) { var app = createApp({ verify: function (req, res, buf) { - throw new Error('unexpected verify call') - } - }) - - var test = request(app).post('/') - test.set('Content-Type', 'application/json; charset=x-bogus') - test.write(Buffer.from('00000000', 'hex')) - test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done) - }) - }) + throw new Error('unexpected verify call'); + }, + }); + + var test = request(app).post('/'); + test.set('Content-Type', 'application/json; charset=x-bogus'); + test.write(Buffer.from('00000000', 'hex')); + test.expect( + 415, + '[charset.unsupported] unsupported charset "X-BOGUS"', + done, + ); + }); + }); describeAsyncHooks('async local storage', function () { before(function () { - var app = express() - var store = { foo: 'bar' } + var app = express(); + var store = { foo: 'bar' }; app.use(function (req, res, next) { - req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage() - req.asyncLocalStorage.run(store, next) - }) + req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage(); + req.asyncLocalStorage.run(store, next); + }); - app.use(express.json()) + app.use(express.json()); app.use(function (req, res, next) { - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); if (local) { - res.setHeader('x-store-foo', String(local.foo)) + res.setHeader('x-store-foo', String(local.foo)); } - next() - }) + next(); + }); app.use(function (err, req, res, next) { - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); if (local) { - res.setHeader('x-store-foo', String(local.foo)) + res.setHeader('x-store-foo', String(local.foo)); } - res.status(err.status || 500) - res.send('[' + err.type + '] ' + err.message) - }) + res.status(err.status || 500); + res.send('[' + err.type + '] ' + err.message); + }); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); - this.app = app - }) + this.app = app; + }); it('should presist store', function (done) { request(this.app) @@ -551,8 +596,8 @@ describe('express.json()', function () { .expect(200) .expect('x-store-foo', 'bar') .expect('{"user":"tobi"}') - .end(done) - }) + .end(done); + }); it('should persist store when unmatched content-type', function (done) { request(this.app) @@ -562,29 +607,39 @@ describe('express.json()', function () { .expect(200) .expect('x-store-foo', 'bar') .expect('') - .end(done) - }) + .end(done); + }); it('should presist store when inflated', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) - test.expect(200) - test.expect('x-store-foo', 'bar') - test.expect('{"name":"论"}') - test.end(done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', + 'hex', + ), + ); + test.expect(200); + test.expect('x-store-foo', 'bar'); + test.expect('{"name":"论"}'); + test.end(done); + }); it('should presist store when inflate error', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) - test.expect(400) - test.expect('x-store-foo', 'bar') - test.end(done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', + 'hex', + ), + ); + test.expect(400); + test.expect('x-store-foo', 'bar'); + test.end(done); + }); it('should presist store when parse error', function (done) { request(this.app) @@ -593,8 +648,8 @@ describe('express.json()', function () { .send('{"user":') .expect(400) .expect('x-store-foo', 'bar') - .end(done) - }) + .end(done); + }); it('should presist store when limit exceeded', function (done) { request(this.app) @@ -603,164 +658,211 @@ describe('express.json()', function () { .send('{"user":"' + Buffer.alloc(1024 * 100, '.').toString() + '"}') .expect(413) .expect('x-store-foo', 'bar') - .end(done) - }) - }) + .end(done); + }); + }); describe('charset', function () { before(function () { - this.app = createApp() - }) + this.app = createApp(); + }); it('should parse utf-8', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/json; charset=utf-8') - test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/json; charset=utf-8'); + test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')); + test.expect(200, '{"name":"论"}', done); + }); it('should parse utf-16', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/json; charset=utf-16') - test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/json; charset=utf-16'); + test.write( + Buffer.from( + 'feff007b0022006e0061006d00650022003a00228bba0022007d', + 'hex', + ), + ); + test.expect(200, '{"name":"论"}', done); + }); it('should parse when content-length != char length', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/json; charset=utf-8') - test.set('Content-Length', '13') - test.write(Buffer.from('7b2274657374223a22c3a5227d', 'hex')) - test.expect(200, '{"test":"å"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/json; charset=utf-8'); + test.set('Content-Length', '13'); + test.write(Buffer.from('7b2274657374223a22c3a5227d', 'hex')); + test.expect(200, '{"test":"å"}', done); + }); it('should default to utf-8', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/json'); + test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')); + test.expect(200, '{"name":"论"}', done); + }); it('should fail on unknown charset', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/json; charset=koi8-r') - test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex')) - test.expect(415, '[charset.unsupported] unsupported charset "KOI8-R"', done) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/json; charset=koi8-r'); + test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex')); + test.expect( + 415, + '[charset.unsupported] unsupported charset "KOI8-R"', + done, + ); + }); + }); describe('encoding', function () { before(function () { - this.app = createApp({ limit: '1kb' }) - }) + this.app = createApp({ limit: '1kb' }); + }); it('should parse without encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/json'); + test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')); + test.expect(200, '{"name":"论"}', done); + }); it('should support identity encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'identity') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'identity'); + test.set('Content-Type', 'application/json'); + test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')); + test.expect(200, '{"name":"论"}', done); + }); it('should support gzip encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', + 'hex', + ), + ); + test.expect(200, '{"name":"论"}', done); + }); it('should support deflate encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'deflate') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('789cab56ca4bcc4d55b2527ab16e97522d00274505ac', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'deflate'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from('789cab56ca4bcc4d55b2527ab16e97522d00274505ac', 'hex'), + ); + test.expect(200, '{"name":"论"}', done); + }); it('should be case-insensitive', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'GZIP') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'GZIP'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', + 'hex', + ), + ); + test.expect(200, '{"name":"论"}', done); + }); it('should 415 on unknown encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'nulls') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('000000000000', 'hex')) - test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'nulls'); + test.set('Content-Type', 'application/json'); + test.write(Buffer.from('000000000000', 'hex')); + test.expect( + 415, + '[encoding.unsupported] unsupported content encoding "nulls"', + done, + ); + }); it('should 400 on malformed encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) - test.expect(400, done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', + 'hex', + ), + ); + test.expect(400, done); + }); it('should 413 when inflated value exceeds limit', function (done) { // gzip'd data exceeds 1kb, but deflated below 1kb - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/json') - test.write(Buffer.from('1f8b080000000000000bedc1010d000000c2a0f74f6d0f071400000000000000', 'hex')) - test.write(Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex')) - test.write(Buffer.from('0000000000000000004f0625b3b71650c30000', 'hex')) - test.expect(413, done) - }) - }) -}) - -function createApp (options) { - var app = express() - - app.use(express.json(options)) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/json'); + test.write( + Buffer.from( + '1f8b080000000000000bedc1010d000000c2a0f74f6d0f071400000000000000', + 'hex', + ), + ); + test.write( + Buffer.from( + '0000000000000000000000000000000000000000000000000000000000000000', + 'hex', + ), + ); + test.write(Buffer.from('0000000000000000004f0625b3b71650c30000', 'hex')); + test.expect(413, done); + }); + }); +}); + +function createApp(options) { + var app = express(); + + app.use(express.json(options)); app.use(function (err, req, res, next) { // console.log(err) - res.status(err.status || 500) - res.send(String(req.headers['x-error-property'] - ? err[req.headers['x-error-property']] - : ('[' + err.type + '] ' + err.message))) - }) + res.status(err.status || 500); + res.send( + String( + req.headers['x-error-property'] + ? err[req.headers['x-error-property']] + : '[' + err.type + '] ' + err.message, + ), + ); + }); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); - return app + return app; } -function parseError (str) { +function parseError(str) { try { - JSON.parse(str); throw new SyntaxError('strict violation') + JSON.parse(str); + throw new SyntaxError('strict violation'); } catch (e) { - return e.message + return e.message; } } -function shouldContainInBody (str) { +function shouldContainInBody(str) { return function (res) { - assert.ok(res.text.indexOf(str) !== -1, - 'expected \'' + res.text + '\' to contain \'' + str + '\'') - } + assert.ok( + res.text.indexOf(str) !== -1, + "expected '" + res.text + "' to contain '" + str + "'", + ); + }; } -function tryRequire (name) { +function tryRequire(name) { try { - return require(name) + return require(name); } catch (e) { - return {} + return {}; } } diff --git a/test/express.raw.js b/test/express.raw.js index f6513a7d48d..f3bff73efd8 100644 --- a/test/express.raw.js +++ b/test/express.raw.js @@ -1,60 +1,59 @@ -'use strict' +'use strict'; -var assert = require('assert') -var asyncHooks = tryRequire('async_hooks') -var Buffer = require('safe-buffer').Buffer -var express = require('..') -var request = require('supertest') +var assert = require('assert'); +var asyncHooks = tryRequire('async_hooks'); +var Buffer = require('safe-buffer').Buffer; +var express = require('..'); +var request = require('supertest'); -var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function' - ? describe - : describe.skip +var describeAsyncHooks = + typeof asyncHooks.AsyncLocalStorage === 'function' ? describe : describe.skip; describe('express.raw()', function () { before(function () { - this.app = createApp() - }) + this.app = createApp(); + }); it('should parse application/octet-stream', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/octet-stream') .send('the user is tobi') - .expect(200, { buf: '746865207573657220697320746f6269' }, done) - }) + .expect(200, { buf: '746865207573657220697320746f6269' }, done); + }); it('should 400 when invalid content-length', function (done) { - var app = express() + var app = express(); app.use(function (req, res, next) { - req.headers['content-length'] = '20' // bad length - next() - }) + req.headers['content-length'] = '20'; // bad length + next(); + }); - app.use(express.raw()) + app.use(express.raw()); app.post('/', function (req, res) { if (Buffer.isBuffer(req.body)) { - res.json({ buf: req.body.toString('hex') }) + res.json({ buf: req.body.toString('hex') }); } else { - res.json(req.body) + res.json(req.body); } - }) + }); request(app) .post('/') .set('Content-Type', 'application/octet-stream') .send('stuff') - .expect(400, /content length/, done) - }) + .expect(400, /content length/, done); + }); it('should handle Content-Length: 0', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/octet-stream') .set('Content-Length', '0') - .expect(200, { buf: '' }, done) - }) + .expect(200, { buf: '' }, done); + }); it('should handle empty message-body', function (done) { request(this.app) @@ -62,315 +61,339 @@ describe('express.raw()', function () { .set('Content-Type', 'application/octet-stream') .set('Transfer-Encoding', 'chunked') .send('') - .expect(200, { buf: '' }, done) - }) + .expect(200, { buf: '' }, done); + }); it('should handle duplicated middleware', function (done) { - var app = express() + var app = express(); - app.use(express.raw()) - app.use(express.raw()) + app.use(express.raw()); + app.use(express.raw()); app.post('/', function (req, res) { if (Buffer.isBuffer(req.body)) { - res.json({ buf: req.body.toString('hex') }) + res.json({ buf: req.body.toString('hex') }); } else { - res.json(req.body) + res.json(req.body); } - }) + }); request(app) .post('/') .set('Content-Type', 'application/octet-stream') .send('the user is tobi') - .expect(200, { buf: '746865207573657220697320746f6269' }, done) - }) + .expect(200, { buf: '746865207573657220697320746f6269' }, done); + }); describe('with limit option', function () { it('should 413 when over limit with Content-Length', function (done) { - var buf = Buffer.alloc(1028, '.') - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.set('Content-Length', '1028') - test.write(buf) - test.expect(413, done) - }) + var buf = Buffer.alloc(1028, '.'); + var app = createApp({ limit: '1kb' }); + var test = request(app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.set('Content-Length', '1028'); + test.write(buf); + test.expect(413, done); + }); it('should 413 when over limit with chunked encoding', function (done) { - var buf = Buffer.alloc(1028, '.') - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.set('Transfer-Encoding', 'chunked') - test.write(buf) - test.expect(413, done) - }) + var buf = Buffer.alloc(1028, '.'); + var app = createApp({ limit: '1kb' }); + var test = request(app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.set('Transfer-Encoding', 'chunked'); + test.write(buf); + test.expect(413, done); + }); it('should 413 when inflated body over limit', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a14704040000', 'hex')) - test.expect(413, done) - }) + var app = createApp({ limit: '1kb' }); + var test = request(app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/octet-stream'); + test.write( + Buffer.from( + '1f8b080000000000000ad3d31b05a360148c64000087e5a14704040000', + 'hex', + ), + ); + test.expect(413, done); + }); it('should accept number of bytes', function (done) { - var buf = Buffer.alloc(1028, '.') - var app = createApp({ limit: 1024 }) - var test = request(app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.write(buf) - test.expect(413, done) - }) + var buf = Buffer.alloc(1028, '.'); + var app = createApp({ limit: 1024 }); + var test = request(app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.write(buf); + test.expect(413, done); + }); it('should not change when options altered', function (done) { - var buf = Buffer.alloc(1028, '.') - var options = { limit: '1kb' } - var app = createApp(options) + var buf = Buffer.alloc(1028, '.'); + var options = { limit: '1kb' }; + var app = createApp(options); - options.limit = '100kb' + options.limit = '100kb'; - var test = request(app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.write(buf) - test.expect(413, done) - }) + var test = request(app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.write(buf); + test.expect(413, done); + }); it('should not hang response', function (done) { - var buf = Buffer.alloc(10240, '.') - var app = createApp({ limit: '8kb' }) - var test = request(app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.write(buf) - test.write(buf) - test.write(buf) - test.expect(413, done) - }) + var buf = Buffer.alloc(10240, '.'); + var app = createApp({ limit: '8kb' }); + var test = request(app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.write(buf); + test.write(buf); + test.write(buf); + test.expect(413, done); + }); it('should not error when inflating', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a147040400', 'hex')) - test.expect(413, done) - }) - }) + var app = createApp({ limit: '1kb' }); + var test = request(app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/octet-stream'); + test.write( + Buffer.from( + '1f8b080000000000000ad3d31b05a360148c64000087e5a147040400', + 'hex', + ), + ); + test.expect(413, done); + }); + }); describe('with inflate option', function () { describe('when false', function () { before(function () { - this.app = createApp({ inflate: false }) - }) + this.app = createApp({ inflate: false }); + }); it('should not accept content-encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(415, '[encoding.unsupported] content encoding unsupported', done) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/octet-stream'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect( + 415, + '[encoding.unsupported] content encoding unsupported', + done, + ); + }); + }); describe('when true', function () { before(function () { - this.app = createApp({ inflate: true }) - }) + this.app = createApp({ inflate: true }); + }); it('should accept content-encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(200, { buf: '6e616d653de8aeba' }, done) - }) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/octet-stream'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect(200, { buf: '6e616d653de8aeba' }, done); + }); + }); + }); describe('with type option', function () { describe('when "application/vnd+octets"', function () { before(function () { - this.app = createApp({ type: 'application/vnd+octets' }) - }) + this.app = createApp({ type: 'application/vnd+octets' }); + }); it('should parse for custom type', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/vnd+octets') - test.write(Buffer.from('000102', 'hex')) - test.expect(200, { buf: '000102' }, done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/vnd+octets'); + test.write(Buffer.from('000102', 'hex')); + test.expect(200, { buf: '000102' }, done); + }); it('should ignore standard type', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('000102', 'hex')) - test.expect(200, '', done) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.write(Buffer.from('000102', 'hex')); + test.expect(200, '', done); + }); + }); describe('when ["application/octet-stream", "application/vnd+octets"]', function () { before(function () { this.app = createApp({ - type: ['application/octet-stream', 'application/vnd+octets'] - }) - }) + type: ['application/octet-stream', 'application/vnd+octets'], + }); + }); it('should parse "application/octet-stream"', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('000102', 'hex')) - test.expect(200, { buf: '000102' }, done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.write(Buffer.from('000102', 'hex')); + test.expect(200, { buf: '000102' }, done); + }); it('should parse "application/vnd+octets"', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/vnd+octets') - test.write(Buffer.from('000102', 'hex')) - test.expect(200, { buf: '000102' }, done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/vnd+octets'); + test.write(Buffer.from('000102', 'hex')); + test.expect(200, { buf: '000102' }, done); + }); it('should ignore "application/x-foo"', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/x-foo') - test.write(Buffer.from('000102', 'hex')) - test.expect(200, '', done) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/x-foo'); + test.write(Buffer.from('000102', 'hex')); + test.expect(200, '', done); + }); + }); describe('when a function', function () { it('should parse when truthy value returned', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - return req.headers['content-type'] === 'application/vnd.octet' + function accept(req) { + return req.headers['content-type'] === 'application/vnd.octet'; } - var test = request(app).post('/') - test.set('Content-Type', 'application/vnd.octet') - test.write(Buffer.from('000102', 'hex')) - test.expect(200, { buf: '000102' }, done) - }) + var test = request(app).post('/'); + test.set('Content-Type', 'application/vnd.octet'); + test.write(Buffer.from('000102', 'hex')); + test.expect(200, { buf: '000102' }, done); + }); it('should work without content-type', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - return true + function accept(req) { + return true; } - var test = request(app).post('/') - test.write(Buffer.from('000102', 'hex')) - test.expect(200, { buf: '000102' }, done) - }) + var test = request(app).post('/'); + test.write(Buffer.from('000102', 'hex')); + test.expect(200, { buf: '000102' }, done); + }); it('should not invoke without a body', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - throw new Error('oops!') + function accept(req) { + throw new Error('oops!'); } - request(app) - .get('/') - .expect(404, done) - }) - }) - }) + request(app).get('/').expect(404, done); + }); + }); + }); describe('with verify option', function () { it('should assert value is function', function () { - assert.throws(createApp.bind(null, { verify: 'lol' }), - /TypeError: option verify must be function/) - }) + assert.throws( + createApp.bind(null, { verify: 'lol' }), + /TypeError: option verify must be function/, + ); + }); it('should error from verify', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x00) throw new Error('no leading null') - } - }) + if (buf[0] === 0x00) throw new Error('no leading null'); + }, + }); - var test = request(app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('000102', 'hex')) - test.expect(403, '[entity.verify.failed] no leading null', done) - }) + var test = request(app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.write(Buffer.from('000102', 'hex')); + test.expect(403, '[entity.verify.failed] no leading null', done); + }); it('should allow custom codes', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] !== 0x00) return - var err = new Error('no leading null') - err.status = 400 - throw err - } - }) - - var test = request(app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('000102', 'hex')) - test.expect(400, '[entity.verify.failed] no leading null', done) - }) + if (buf[0] !== 0x00) return; + var err = new Error('no leading null'); + err.status = 400; + throw err; + }, + }); + + var test = request(app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.write(Buffer.from('000102', 'hex')); + test.expect(400, '[entity.verify.failed] no leading null', done); + }); it('should allow pass-through', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x00) throw new Error('no leading null') - } - }) + if (buf[0] === 0x00) throw new Error('no leading null'); + }, + }); - var test = request(app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('0102', 'hex')) - test.expect(200, { buf: '0102' }, done) - }) - }) + var test = request(app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.write(Buffer.from('0102', 'hex')); + test.expect(200, { buf: '0102' }, done); + }); + }); describeAsyncHooks('async local storage', function () { before(function () { - var app = express() - var store = { foo: 'bar' } + var app = express(); + var store = { foo: 'bar' }; app.use(function (req, res, next) { - req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage() - req.asyncLocalStorage.run(store, next) - }) + req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage(); + req.asyncLocalStorage.run(store, next); + }); - app.use(express.raw()) + app.use(express.raw()); app.use(function (req, res, next) { - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); if (local) { - res.setHeader('x-store-foo', String(local.foo)) + res.setHeader('x-store-foo', String(local.foo)); } - next() - }) + next(); + }); app.use(function (err, req, res, next) { - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); if (local) { - res.setHeader('x-store-foo', String(local.foo)) + res.setHeader('x-store-foo', String(local.foo)); } - res.status(err.status || 500) - res.send('[' + err.type + '] ' + err.message) - }) + res.status(err.status || 500); + res.send('[' + err.type + '] ' + err.message); + }); app.post('/', function (req, res) { if (Buffer.isBuffer(req.body)) { - res.json({ buf: req.body.toString('hex') }) + res.json({ buf: req.body.toString('hex') }); } else { - res.json(req.body) + res.json(req.body); } - }) + }); - this.app = app - }) + this.app = app; + }); it('should presist store', function (done) { request(this.app) @@ -380,8 +403,8 @@ describe('express.raw()', function () { .expect(200) .expect('x-store-foo', 'bar') .expect({ buf: '746865207573657220697320746f6269' }) - .end(done) - }) + .end(done); + }); it('should presist store when unmatched content-type', function (done) { request(this.app) @@ -390,29 +413,39 @@ describe('express.raw()', function () { .send('buzz') .expect(200) .expect('x-store-foo', 'bar') - .end(done) - }) + .end(done); + }); it('should presist store when inflated', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(200) - test.expect('x-store-foo', 'bar') - test.expect({ buf: '6e616d653de8aeba' }) - test.end(done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/octet-stream'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect(200); + test.expect('x-store-foo', 'bar'); + test.expect({ buf: '6e616d653de8aeba' }); + test.end(done); + }); it('should presist store when inflate error', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', 'hex')) - test.expect(400) - test.expect('x-store-foo', 'bar') - test.end(done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/octet-stream'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', + 'hex', + ), + ); + test.expect(400); + test.expect('x-store-foo', 'bar'); + test.end(done); + }); it('should presist store when limit exceeded', function (done) { request(this.app) @@ -421,104 +454,122 @@ describe('express.raw()', function () { .send('the user is ' + Buffer.alloc(1024 * 100, '.').toString()) .expect(413) .expect('x-store-foo', 'bar') - .end(done) - }) - }) + .end(done); + }); + }); describe('charset', function () { before(function () { - this.app = createApp() - }) + this.app = createApp(); + }); it('should ignore charset', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/octet-stream; charset=utf-8') - test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) - test.expect(200, { buf: '6e616d6520697320e8aeba' }, done) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/octet-stream; charset=utf-8'); + test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')); + test.expect(200, { buf: '6e616d6520697320e8aeba' }, done); + }); + }); describe('encoding', function () { before(function () { - this.app = createApp({ limit: '10kb' }) - }) + this.app = createApp({ limit: '10kb' }); + }); it('should parse without encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('6e616d653de8aeba', 'hex')) - test.expect(200, { buf: '6e616d653de8aeba' }, done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/octet-stream'); + test.write(Buffer.from('6e616d653de8aeba', 'hex')); + test.expect(200, { buf: '6e616d653de8aeba' }, done); + }); it('should support identity encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'identity') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('6e616d653de8aeba', 'hex')) - test.expect(200, { buf: '6e616d653de8aeba' }, done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'identity'); + test.set('Content-Type', 'application/octet-stream'); + test.write(Buffer.from('6e616d653de8aeba', 'hex')); + test.expect(200, { buf: '6e616d653de8aeba' }, done); + }); it('should support gzip encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(200, { buf: '6e616d653de8aeba' }, done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/octet-stream'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect(200, { buf: '6e616d653de8aeba' }, done); + }); it('should support deflate encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'deflate') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex')) - test.expect(200, { buf: '6e616d653de8aeba' }, done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'deflate'); + test.set('Content-Type', 'application/octet-stream'); + test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex')); + test.expect(200, { buf: '6e616d653de8aeba' }, done); + }); it('should be case-insensitive', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'GZIP') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(200, { buf: '6e616d653de8aeba' }, done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'GZIP'); + test.set('Content-Type', 'application/octet-stream'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect(200, { buf: '6e616d653de8aeba' }, done); + }); it('should 415 on unknown encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'nulls') - test.set('Content-Type', 'application/octet-stream') - test.write(Buffer.from('000000000000', 'hex')) - test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done) - }) - }) -}) - -function createApp (options) { - var app = express() - - app.use(express.raw(options)) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'nulls'); + test.set('Content-Type', 'application/octet-stream'); + test.write(Buffer.from('000000000000', 'hex')); + test.expect( + 415, + '[encoding.unsupported] unsupported content encoding "nulls"', + done, + ); + }); + }); +}); + +function createApp(options) { + var app = express(); + + app.use(express.raw(options)); app.use(function (err, req, res, next) { - res.status(err.status || 500) - res.send(String(req.headers['x-error-property'] - ? err[req.headers['x-error-property']] - : ('[' + err.type + '] ' + err.message))) - }) + res.status(err.status || 500); + res.send( + String( + req.headers['x-error-property'] + ? err[req.headers['x-error-property']] + : '[' + err.type + '] ' + err.message, + ), + ); + }); app.post('/', function (req, res) { if (Buffer.isBuffer(req.body)) { - res.json({ buf: req.body.toString('hex') }) + res.json({ buf: req.body.toString('hex') }); } else { - res.json(req.body) + res.json(req.body); } - }) + }); - return app + return app; } -function tryRequire (name) { +function tryRequire(name) { try { - return require(name) + return require(name); } catch (e) { - return {} + return {}; } } diff --git a/test/express.static.js b/test/express.static.js index e5100e8c8d2..f6da2fbfbb8 100644 --- a/test/express.static.js +++ b/test/express.static.js @@ -1,726 +1,706 @@ -'use strict' +'use strict'; -var assert = require('assert') -var Buffer = require('safe-buffer').Buffer -var express = require('..') -var path = require('path') -var request = require('supertest') -var utils = require('./support/utils') +var assert = require('assert'); +var Buffer = require('safe-buffer').Buffer; +var express = require('..'); +var path = require('path'); +var request = require('supertest'); +var utils = require('./support/utils'); -var fixtures = path.join(__dirname, '/fixtures') -var relative = path.relative(process.cwd(), fixtures) +var fixtures = path.join(__dirname, '/fixtures'); +var relative = path.relative(process.cwd(), fixtures); -var skipRelative = ~relative.indexOf('..') || path.resolve(relative) === relative +var skipRelative = + ~relative.indexOf('..') || path.resolve(relative) === relative; describe('express.static()', function () { describe('basic operations', function () { before(function () { - this.app = createApp() - }) + this.app = createApp(); + }); it('should require root path', function () { - assert.throws(express.static.bind(), /root path required/) - }) + assert.throws(express.static.bind(), /root path required/); + }); it('should require root path to be string', function () { - assert.throws(express.static.bind(null, 42), /root path.*string/) - }) + assert.throws(express.static.bind(null, 42), /root path.*string/); + }); it('should serve static files', function (done) { - request(this.app) - .get('/todo.txt') - .expect(200, '- groceries', done) - }) + request(this.app).get('/todo.txt').expect(200, '- groceries', done); + }); it('should support nesting', function (done) { - request(this.app) - .get('/users/tobi.txt') - .expect(200, 'ferret', done) - }) + request(this.app).get('/users/tobi.txt').expect(200, 'ferret', done); + }); it('should set Content-Type', function (done) { request(this.app) .get('/todo.txt') .expect('Content-Type', 'text/plain; charset=utf-8') - .expect(200, done) - }) + .expect(200, done); + }); it('should set Last-Modified', function (done) { request(this.app) .get('/todo.txt') .expect('Last-Modified', /\d{2} \w{3} \d{4}/) - .expect(200, done) - }) + .expect(200, done); + }); it('should default max-age=0', function (done) { request(this.app) .get('/todo.txt') .expect('Cache-Control', 'public, max-age=0') - .expect(200, done) - }) + .expect(200, done); + }); it('should support urlencoded pathnames', function (done) { - request(this.app) - .get('/%25%20of%20dogs.txt') - .expect(200, '20%', done) - }) + request(this.app).get('/%25%20of%20dogs.txt').expect(200, '20%', done); + }); it('should not choke on auth-looking URL', function (done) { - request(this.app) - .get('//todo@txt') - .expect(404, 'Not Found', done) - }) + request(this.app).get('//todo@txt').expect(404, 'Not Found', done); + }); it('should support index.html', function (done) { request(this.app) .get('/users/') .expect(200) .expect('Content-Type', /html/) - .expect('

        tobi, loki, jane

        ', done) - }) + .expect('

        tobi, loki, jane

        ', done); + }); it('should support ../', function (done) { request(this.app) .get('/users/../todo.txt') - .expect(200, '- groceries', done) - }) + .expect(200, '- groceries', done); + }); it('should support HEAD', function (done) { request(this.app) .head('/todo.txt') .expect(200) .expect(utils.shouldNotHaveBody()) - .end(done) - }) + .end(done); + }); it('should skip POST requests', function (done) { - request(this.app) - .post('/todo.txt') - .expect(404, 'Not Found', done) - }) + request(this.app).post('/todo.txt').expect(404, 'Not Found', done); + }); it('should support conditional requests', function (done) { - var app = this.app + var app = this.app; request(app) .get('/todo.txt') .end(function (err, res) { - if (err) throw err + if (err) throw err; request(app) .get('/todo.txt') .set('If-None-Match', res.headers.etag) - .expect(304, done) - }) - }) + .expect(304, done); + }); + }); it('should support precondition checks', function (done) { request(this.app) .get('/todo.txt') .set('If-Match', '"foo"') - .expect(412, done) - }) + .expect(412, done); + }); it('should serve zero-length files', function (done) { - request(this.app) - .get('/empty.txt') - .expect(200, '', done) - }) + request(this.app).get('/empty.txt').expect(200, '', done); + }); it('should ignore hidden files', function (done) { - request(this.app) - .get('/.name') - .expect(404, 'Not Found', done) - }) + request(this.app).get('/.name').expect(404, 'Not Found', done); + }); }); - (skipRelative ? describe.skip : describe)('current dir', function () { before(function () { - this.app = createApp('.') - }) + this.app = createApp('.'); + }); it('should be served with "."', function (done) { - var dest = relative.split(path.sep).join('/') + var dest = relative.split(path.sep).join('/'); request(this.app) .get('/' + dest + '/todo.txt') - .expect(200, '- groceries', done) - }) - }) + .expect(200, '- groceries', done); + }); + }); describe('acceptRanges', function () { describe('when false', function () { it('should not include Accept-Ranges', function (done) { - request(createApp(fixtures, { 'acceptRanges': false })) + request(createApp(fixtures, { acceptRanges: false })) .get('/nums.txt') .expect(utils.shouldNotHaveHeader('Accept-Ranges')) - .expect(200, '123456789', done) - }) + .expect(200, '123456789', done); + }); it('should ignore Rage request header', function (done) { - request(createApp(fixtures, { 'acceptRanges': false })) + request(createApp(fixtures, { acceptRanges: false })) .get('/nums.txt') .set('Range', 'bytes=0-3') .expect(utils.shouldNotHaveHeader('Accept-Ranges')) .expect(utils.shouldNotHaveHeader('Content-Range')) - .expect(200, '123456789', done) - }) - }) + .expect(200, '123456789', done); + }); + }); describe('when true', function () { it('should include Accept-Ranges', function (done) { - request(createApp(fixtures, { 'acceptRanges': true })) + request(createApp(fixtures, { acceptRanges: true })) .get('/nums.txt') .expect('Accept-Ranges', 'bytes') - .expect(200, '123456789', done) - }) + .expect(200, '123456789', done); + }); it('should obey Rage request header', function (done) { - request(createApp(fixtures, { 'acceptRanges': true })) + request(createApp(fixtures, { acceptRanges: true })) .get('/nums.txt') .set('Range', 'bytes=0-3') .expect('Accept-Ranges', 'bytes') .expect('Content-Range', 'bytes 0-3/9') - .expect(206, '1234', done) - }) - }) - }) + .expect(206, '1234', done); + }); + }); + }); describe('cacheControl', function () { describe('when false', function () { it('should not include Cache-Control', function (done) { - request(createApp(fixtures, { 'cacheControl': false })) + request(createApp(fixtures, { cacheControl: false })) .get('/nums.txt') .expect(utils.shouldNotHaveHeader('Cache-Control')) - .expect(200, '123456789', done) - }) + .expect(200, '123456789', done); + }); it('should ignore maxAge', function (done) { - request(createApp(fixtures, { 'cacheControl': false, 'maxAge': 12000 })) + request(createApp(fixtures, { cacheControl: false, maxAge: 12000 })) .get('/nums.txt') .expect(utils.shouldNotHaveHeader('Cache-Control')) - .expect(200, '123456789', done) - }) - }) + .expect(200, '123456789', done); + }); + }); describe('when true', function () { it('should include Cache-Control', function (done) { - request(createApp(fixtures, { 'cacheControl': true })) + request(createApp(fixtures, { cacheControl: true })) .get('/nums.txt') .expect('Cache-Control', 'public, max-age=0') - .expect(200, '123456789', done) - }) - }) - }) + .expect(200, '123456789', done); + }); + }); + }); describe('extensions', function () { it('should be not be enabled by default', function (done) { - request(createApp(fixtures)) - .get('/todo') - .expect(404, done) - }) + request(createApp(fixtures)).get('/todo').expect(404, done); + }); it('should be configurable', function (done) { - request(createApp(fixtures, { 'extensions': 'txt' })) + request(createApp(fixtures, { extensions: 'txt' })) .get('/todo') - .expect(200, '- groceries', done) - }) + .expect(200, '- groceries', done); + }); it('should support disabling extensions', function (done) { - request(createApp(fixtures, { 'extensions': false })) + request(createApp(fixtures, { extensions: false })) .get('/todo') - .expect(404, done) - }) + .expect(404, done); + }); it('should support fallbacks', function (done) { - request(createApp(fixtures, { 'extensions': ['htm', 'html', 'txt'] })) + request(createApp(fixtures, { extensions: ['htm', 'html', 'txt'] })) .get('/todo') - .expect(200, '
      • groceries
      • ', done) - }) + .expect(200, '
      • groceries
      • ', done); + }); it('should 404 if nothing found', function (done) { - request(createApp(fixtures, { 'extensions': ['htm', 'html', 'txt'] })) + request(createApp(fixtures, { extensions: ['htm', 'html', 'txt'] })) .get('/bob') - .expect(404, done) - }) - }) + .expect(404, done); + }); + }); describe('fallthrough', function () { it('should default to true', function (done) { request(createApp()) .get('/does-not-exist') - .expect(404, 'Not Found', done) - }) + .expect(404, 'Not Found', done); + }); describe('when true', function () { before(function () { - this.app = createApp(fixtures, { 'fallthrough': true }) - }) + this.app = createApp(fixtures, { fallthrough: true }); + }); it('should fall-through when OPTIONS request', function (done) { - request(this.app) - .options('/todo.txt') - .expect(404, 'Not Found', done) - }) + request(this.app).options('/todo.txt').expect(404, 'Not Found', done); + }); it('should fall-through when URL malformed', function (done) { - request(this.app) - .get('/%') - .expect(404, 'Not Found', done) - }) + request(this.app).get('/%').expect(404, 'Not Found', done); + }); it('should fall-through when traversing past root', function (done) { request(this.app) .get('/users/../../todo.txt') - .expect(404, 'Not Found', done) - }) + .expect(404, 'Not Found', done); + }); it('should fall-through when URL too long', function (done) { - var app = express() - var root = fixtures + Array(10000).join('/foobar') + var app = express(); + var root = fixtures + Array(10000).join('/foobar'); - app.use(express.static(root, { 'fallthrough': true })) + app.use(express.static(root, { fallthrough: true })); app.use(function (req, res, next) { - res.sendStatus(404) - }) + res.sendStatus(404); + }); - request(app) - .get('/') - .expect(404, 'Not Found', done) - }) + request(app).get('/').expect(404, 'Not Found', done); + }); describe('with redirect: true', function () { before(function () { - this.app = createApp(fixtures, { 'fallthrough': true, 'redirect': true }) - }) + this.app = createApp(fixtures, { fallthrough: true, redirect: true }); + }); it('should fall-through when directory', function (done) { - request(this.app) - .get('/pets/') - .expect(404, 'Not Found', done) - }) + request(this.app).get('/pets/').expect(404, 'Not Found', done); + }); it('should redirect when directory without slash', function (done) { request(this.app) .get('/pets') - .expect(301, /Redirecting/, done) - }) - }) + .expect(301, /Redirecting/, done); + }); + }); describe('with redirect: false', function () { before(function () { - this.app = createApp(fixtures, { 'fallthrough': true, 'redirect': false }) - }) + this.app = createApp(fixtures, { + fallthrough: true, + redirect: false, + }); + }); it('should fall-through when directory', function (done) { - request(this.app) - .get('/pets/') - .expect(404, 'Not Found', done) - }) + request(this.app).get('/pets/').expect(404, 'Not Found', done); + }); it('should fall-through when directory without slash', function (done) { - request(this.app) - .get('/pets') - .expect(404, 'Not Found', done) - }) - }) - }) + request(this.app).get('/pets').expect(404, 'Not Found', done); + }); + }); + }); describe('when false', function () { before(function () { - this.app = createApp(fixtures, { 'fallthrough': false }) - }) + this.app = createApp(fixtures, { fallthrough: false }); + }); it('should 405 when OPTIONS request', function (done) { request(this.app) .options('/todo.txt') .expect('Allow', 'GET, HEAD') - .expect(405, done) - }) + .expect(405, done); + }); it('should 400 when URL malformed', function (done) { request(this.app) .get('/%') - .expect(400, /BadRequestError/, done) - }) + .expect(400, /BadRequestError/, done); + }); it('should 403 when traversing past root', function (done) { request(this.app) .get('/users/../../todo.txt') - .expect(403, /ForbiddenError/, done) - }) + .expect(403, /ForbiddenError/, done); + }); it('should 404 when URL too long', function (done) { - var app = express() - var root = fixtures + Array(10000).join('/foobar') + var app = express(); + var root = fixtures + Array(10000).join('/foobar'); - app.use(express.static(root, { 'fallthrough': false })) + app.use(express.static(root, { fallthrough: false })); app.use(function (req, res, next) { - res.sendStatus(404) - }) + res.sendStatus(404); + }); request(app) .get('/') - .expect(404, /ENAMETOOLONG/, done) - }) + .expect(404, /ENAMETOOLONG/, done); + }); describe('with redirect: true', function () { before(function () { - this.app = createApp(fixtures, { 'fallthrough': false, 'redirect': true }) - }) + this.app = createApp(fixtures, { + fallthrough: false, + redirect: true, + }); + }); it('should 404 when directory', function (done) { request(this.app) .get('/pets/') - .expect(404, /NotFoundError|ENOENT/, done) - }) + .expect(404, /NotFoundError|ENOENT/, done); + }); it('should redirect when directory without slash', function (done) { request(this.app) .get('/pets') - .expect(301, /Redirecting/, done) - }) - }) + .expect(301, /Redirecting/, done); + }); + }); describe('with redirect: false', function () { before(function () { - this.app = createApp(fixtures, { 'fallthrough': false, 'redirect': false }) - }) + this.app = createApp(fixtures, { + fallthrough: false, + redirect: false, + }); + }); it('should 404 when directory', function (done) { request(this.app) .get('/pets/') - .expect(404, /NotFoundError|ENOENT/, done) - }) + .expect(404, /NotFoundError|ENOENT/, done); + }); it('should 404 when directory without slash', function (done) { request(this.app) .get('/pets') - .expect(404, /NotFoundError|ENOENT/, done) - }) - }) - }) - }) + .expect(404, /NotFoundError|ENOENT/, done); + }); + }); + }); + }); describe('hidden files', function () { before(function () { - this.app = createApp(fixtures, { 'dotfiles': 'allow' }) - }) + this.app = createApp(fixtures, { dotfiles: 'allow' }); + }); it('should be served when dotfiles: "allow" is given', function (done) { request(this.app) .get('/.name') .expect(200) .expect(utils.shouldHaveBody(Buffer.from('tobi'))) - .end(done) - }) - }) + .end(done); + }); + }); describe('immutable', function () { it('should default to false', function (done) { request(createApp(fixtures)) .get('/nums.txt') - .expect('Cache-Control', 'public, max-age=0', done) - }) + .expect('Cache-Control', 'public, max-age=0', done); + }); it('should set immutable directive in Cache-Control', function (done) { - request(createApp(fixtures, { 'immutable': true, 'maxAge': '1h' })) + request(createApp(fixtures, { immutable: true, maxAge: '1h' })) .get('/nums.txt') - .expect('Cache-Control', 'public, max-age=3600, immutable', done) - }) - }) + .expect('Cache-Control', 'public, max-age=3600, immutable', done); + }); + }); describe('lastModified', function () { describe('when false', function () { it('should not include Last-Modified', function (done) { - request(createApp(fixtures, { 'lastModified': false })) + request(createApp(fixtures, { lastModified: false })) .get('/nums.txt') .expect(utils.shouldNotHaveHeader('Last-Modified')) - .expect(200, '123456789', done) - }) - }) + .expect(200, '123456789', done); + }); + }); describe('when true', function () { it('should include Last-Modified', function (done) { - request(createApp(fixtures, { 'lastModified': true })) + request(createApp(fixtures, { lastModified: true })) .get('/nums.txt') .expect('Last-Modified', /^\w{3}, \d+ \w+ \d+ \d+:\d+:\d+ \w+$/) - .expect(200, '123456789', done) - }) - }) - }) + .expect(200, '123456789', done); + }); + }); + }); describe('maxAge', function () { it('should accept string', function (done) { - request(createApp(fixtures, { 'maxAge': '30d' })) + request(createApp(fixtures, { maxAge: '30d' })) .get('/todo.txt') - .expect('cache-control', 'public, max-age=' + (60 * 60 * 24 * 30)) - .expect(200, done) - }) + .expect('cache-control', 'public, max-age=' + 60 * 60 * 24 * 30) + .expect(200, done); + }); it('should be reasonable when infinite', function (done) { - request(createApp(fixtures, { 'maxAge': Infinity })) + request(createApp(fixtures, { maxAge: Infinity })) .get('/todo.txt') - .expect('cache-control', 'public, max-age=' + (60 * 60 * 24 * 365)) - .expect(200, done) - }) - }) + .expect('cache-control', 'public, max-age=' + 60 * 60 * 24 * 365) + .expect(200, done); + }); + }); describe('redirect', function () { before(function () { - this.app = express() + this.app = express(); this.app.use(function (req, res, next) { - req.originalUrl = req.url = - req.originalUrl.replace(/\/snow(\/|$)/, '/snow \u2603$1') - next() - }) - this.app.use(express.static(fixtures)) - }) + req.originalUrl = req.url = req.originalUrl.replace( + /\/snow(\/|$)/, + '/snow \u2603$1', + ); + next(); + }); + this.app.use(express.static(fixtures)); + }); it('should redirect directories', function (done) { request(this.app) .get('/users') .expect('Location', '/users/') - .expect(301, done) - }) + .expect(301, done); + }); it('should include HTML link', function (done) { request(this.app) .get('/users') .expect('Location', '/users/') - .expect(301, /\/users\//, done) - }) + .expect(301, /\/users\//, done); + }); it('should redirect directories with query string', function (done) { request(this.app) .get('/users?name=john') .expect('Location', '/users/?name=john') - .expect(301, done) - }) + .expect(301, done); + }); it('should not redirect to protocol-relative locations', function (done) { request(this.app) .get('//users') .expect('Location', '/users/') - .expect(301, done) - }) + .expect(301, done); + }); it('should ensure redirect URL is properly encoded', function (done) { request(this.app) .get('/snow') .expect('Location', '/snow%20%E2%98%83/') .expect('Content-Type', /html/) - .expect(301, />Redirecting to \/snow%20%E2%98%83\/Redirecting to \/snow%20%E2%98%83\/tobi') - .expect(200, '"tobi"', done) - }) + .expect(200, '"tobi"', done); + }); it('should ignore standard type', function (done) { request(this.app) .post('/') .set('Content-Type', 'text/plain') .send('user is tobi') - .expect(200, '', done) - }) - }) + .expect(200, '', done); + }); + }); describe('when ["text/html", "text/plain"]', function () { before(function () { - this.app = createApp({ type: ['text/html', 'text/plain'] }) - }) + this.app = createApp({ type: ['text/html', 'text/plain'] }); + }); it('should parse "text/html"', function (done) { request(this.app) .post('/') .set('Content-Type', 'text/html') .send('tobi') - .expect(200, '"tobi"', done) - }) + .expect(200, '"tobi"', done); + }); it('should parse "text/plain"', function (done) { request(this.app) .post('/') .set('Content-Type', 'text/plain') .send('tobi') - .expect(200, '"tobi"', done) - }) + .expect(200, '"tobi"', done); + }); it('should ignore "text/xml"', function (done) { request(this.app) .post('/') .set('Content-Type', 'text/xml') .send('tobi') - .expect(200, '', done) - }) - }) + .expect(200, '', done); + }); + }); describe('when a function', function () { it('should parse when truthy value returned', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - return req.headers['content-type'] === 'text/vnd.something' + function accept(req) { + return req.headers['content-type'] === 'text/vnd.something'; } request(app) .post('/') .set('Content-Type', 'text/vnd.something') .send('user is tobi') - .expect(200, '"user is tobi"', done) - }) + .expect(200, '"user is tobi"', done); + }); it('should work without content-type', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - return true + function accept(req) { + return true; } - var test = request(app).post('/') - test.write('user is tobi') - test.expect(200, '"user is tobi"', done) - }) + var test = request(app).post('/'); + test.write('user is tobi'); + test.expect(200, '"user is tobi"', done); + }); it('should not invoke without a body', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - throw new Error('oops!') + function accept(req) { + throw new Error('oops!'); } - request(app) - .get('/') - .expect(404, done) - }) - }) - }) + request(app).get('/').expect(404, done); + }); + }); + }); describe('with verify option', function () { it('should assert value is function', function () { - assert.throws(createApp.bind(null, { verify: 'lol' }), - /TypeError: option verify must be function/) - }) + assert.throws( + createApp.bind(null, { verify: 'lol' }), + /TypeError: option verify must be function/, + ); + }); it('should error from verify', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x20) throw new Error('no leading space') - } - }) + if (buf[0] === 0x20) throw new Error('no leading space'); + }, + }); request(app) .post('/') .set('Content-Type', 'text/plain') .send(' user is tobi') - .expect(403, '[entity.verify.failed] no leading space', done) - }) + .expect(403, '[entity.verify.failed] no leading space', done); + }); it('should allow custom codes', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] !== 0x20) return - var err = new Error('no leading space') - err.status = 400 - throw err - } - }) + if (buf[0] !== 0x20) return; + var err = new Error('no leading space'); + err.status = 400; + throw err; + }, + }); request(app) .post('/') .set('Content-Type', 'text/plain') .send(' user is tobi') - .expect(400, '[entity.verify.failed] no leading space', done) - }) + .expect(400, '[entity.verify.failed] no leading space', done); + }); it('should allow pass-through', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x20) throw new Error('no leading space') - } - }) + if (buf[0] === 0x20) throw new Error('no leading space'); + }, + }); request(app) .post('/') .set('Content-Type', 'text/plain') .send('user is tobi') - .expect(200, '"user is tobi"', done) - }) + .expect(200, '"user is tobi"', done); + }); it('should 415 on unknown charset prior to verify', function (done) { var app = createApp({ verify: function (req, res, buf) { - throw new Error('unexpected verify call') - } - }) - - var test = request(app).post('/') - test.set('Content-Type', 'text/plain; charset=x-bogus') - test.write(Buffer.from('00000000', 'hex')) - test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done) - }) - }) + throw new Error('unexpected verify call'); + }, + }); + + var test = request(app).post('/'); + test.set('Content-Type', 'text/plain; charset=x-bogus'); + test.write(Buffer.from('00000000', 'hex')); + test.expect( + 415, + '[charset.unsupported] unsupported charset "X-BOGUS"', + done, + ); + }); + }); describeAsyncHooks('async local storage', function () { before(function () { - var app = express() - var store = { foo: 'bar' } + var app = express(); + var store = { foo: 'bar' }; app.use(function (req, res, next) { - req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage() - req.asyncLocalStorage.run(store, next) - }) + req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage(); + req.asyncLocalStorage.run(store, next); + }); - app.use(express.text()) + app.use(express.text()); app.use(function (req, res, next) { - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); if (local) { - res.setHeader('x-store-foo', String(local.foo)) + res.setHeader('x-store-foo', String(local.foo)); } - next() - }) + next(); + }); app.use(function (err, req, res, next) { - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); if (local) { - res.setHeader('x-store-foo', String(local.foo)) + res.setHeader('x-store-foo', String(local.foo)); } - res.status(err.status || 500) - res.send('[' + err.type + '] ' + err.message) - }) + res.status(err.status || 500); + res.send('[' + err.type + '] ' + err.message); + }); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); - this.app = app - }) + this.app = app; + }); it('should presist store', function (done) { request(this.app) @@ -409,8 +436,8 @@ describe('express.text()', function () { .expect(200) .expect('x-store-foo', 'bar') .expect('"user is tobi"') - .end(done) - }) + .end(done); + }); it('should presist store when unmatched content-type', function (done) { request(this.app) @@ -419,29 +446,39 @@ describe('express.text()', function () { .send('buzz') .expect(200) .expect('x-store-foo', 'bar') - .end(done) - }) + .end(done); + }); it('should presist store when inflated', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'text/plain') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex')) - test.expect(200) - test.expect('x-store-foo', 'bar') - test.expect('"name is 论"') - test.end(done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'text/plain'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', + 'hex', + ), + ); + test.expect(200); + test.expect('x-store-foo', 'bar'); + test.expect('"name is 论"'); + test.end(done); + }); it('should presist store when inflate error', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'text/plain') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b0000', 'hex')) - test.expect(400) - test.expect('x-store-foo', 'bar') - test.end(done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'text/plain'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b0000', + 'hex', + ), + ); + test.expect(400); + test.expect('x-store-foo', 'bar'); + test.end(done); + }); it('should presist store when limit exceeded', function (done) { request(this.app) @@ -450,129 +487,151 @@ describe('express.text()', function () { .send('user is ' + Buffer.alloc(1024 * 100, '.').toString()) .expect(413) .expect('x-store-foo', 'bar') - .end(done) - }) - }) + .end(done); + }); + }); describe('charset', function () { before(function () { - this.app = createApp() - }) + this.app = createApp(); + }); it('should parse utf-8', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'text/plain; charset=utf-8') - test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) - test.expect(200, '"name is 论"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'text/plain; charset=utf-8'); + test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')); + test.expect(200, '"name is 论"', done); + }); it('should parse codepage charsets', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'text/plain; charset=koi8-r') - test.write(Buffer.from('6e616d6520697320cec5d4', 'hex')) - test.expect(200, '"name is нет"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'text/plain; charset=koi8-r'); + test.write(Buffer.from('6e616d6520697320cec5d4', 'hex')); + test.expect(200, '"name is нет"', done); + }); it('should parse when content-length != char length', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'text/plain; charset=utf-8') - test.set('Content-Length', '11') - test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) - test.expect(200, '"name is 论"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'text/plain; charset=utf-8'); + test.set('Content-Length', '11'); + test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')); + test.expect(200, '"name is 论"', done); + }); it('should default to utf-8', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'text/plain') - test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) - test.expect(200, '"name is 论"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'text/plain'); + test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')); + test.expect(200, '"name is 论"', done); + }); it('should 415 on unknown charset', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'text/plain; charset=x-bogus') - test.write(Buffer.from('00000000', 'hex')) - test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'text/plain; charset=x-bogus'); + test.write(Buffer.from('00000000', 'hex')); + test.expect( + 415, + '[charset.unsupported] unsupported charset "X-BOGUS"', + done, + ); + }); + }); describe('encoding', function () { before(function () { - this.app = createApp({ limit: '10kb' }) - }) + this.app = createApp({ limit: '10kb' }); + }); it('should parse without encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'text/plain') - test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) - test.expect(200, '"name is 论"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'text/plain'); + test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')); + test.expect(200, '"name is 论"', done); + }); it('should support identity encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'identity') - test.set('Content-Type', 'text/plain') - test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) - test.expect(200, '"name is 论"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'identity'); + test.set('Content-Type', 'text/plain'); + test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')); + test.expect(200, '"name is 论"', done); + }); it('should support gzip encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'text/plain') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex')) - test.expect(200, '"name is 论"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'text/plain'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', + 'hex', + ), + ); + test.expect(200, '"name is 论"', done); + }); it('should support deflate encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'deflate') - test.set('Content-Type', 'text/plain') - test.write(Buffer.from('789ccb4bcc4d55c82c5678b16e17001a6f050e', 'hex')) - test.expect(200, '"name is 论"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'deflate'); + test.set('Content-Type', 'text/plain'); + test.write(Buffer.from('789ccb4bcc4d55c82c5678b16e17001a6f050e', 'hex')); + test.expect(200, '"name is 论"', done); + }); it('should be case-insensitive', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'GZIP') - test.set('Content-Type', 'text/plain') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex')) - test.expect(200, '"name is 论"', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'GZIP'); + test.set('Content-Type', 'text/plain'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', + 'hex', + ), + ); + test.expect(200, '"name is 论"', done); + }); it('should 415 on unknown encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'nulls') - test.set('Content-Type', 'text/plain') - test.write(Buffer.from('000000000000', 'hex')) - test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done) - }) - }) -}) - -function createApp (options) { - var app = express() - - app.use(express.text(options)) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'nulls'); + test.set('Content-Type', 'text/plain'); + test.write(Buffer.from('000000000000', 'hex')); + test.expect( + 415, + '[encoding.unsupported] unsupported content encoding "nulls"', + done, + ); + }); + }); +}); + +function createApp(options) { + var app = express(); + + app.use(express.text(options)); app.use(function (err, req, res, next) { - res.status(err.status || 500) - res.send(String(req.headers['x-error-property'] - ? err[req.headers['x-error-property']] - : ('[' + err.type + '] ' + err.message))) - }) + res.status(err.status || 500); + res.send( + String( + req.headers['x-error-property'] + ? err[req.headers['x-error-property']] + : '[' + err.type + '] ' + err.message, + ), + ); + }); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); - return app + return app; } -function tryRequire (name) { +function tryRequire(name) { try { - return require(name) + return require(name); } catch (e) { - return {} + return {}; } } diff --git a/test/express.urlencoded.js b/test/express.urlencoded.js index 37afb07f38a..1fac295eccc 100644 --- a/test/express.urlencoded.js +++ b/test/express.urlencoded.js @@ -1,48 +1,47 @@ -'use strict' +'use strict'; -var assert = require('assert') -var asyncHooks = tryRequire('async_hooks') -var Buffer = require('safe-buffer').Buffer -var express = require('..') -var request = require('supertest') +var assert = require('assert'); +var asyncHooks = tryRequire('async_hooks'); +var Buffer = require('safe-buffer').Buffer; +var express = require('..'); +var request = require('supertest'); -var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function' - ? describe - : describe.skip +var describeAsyncHooks = + typeof asyncHooks.AsyncLocalStorage === 'function' ? describe : describe.skip; describe('express.urlencoded()', function () { before(function () { - this.app = createApp() - }) + this.app = createApp(); + }); it('should parse x-www-form-urlencoded', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user=tobi') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should 400 when invalid content-length', function (done) { - var app = express() + var app = express(); app.use(function (req, res, next) { - req.headers['content-length'] = '20' // bad length - next() - }) + req.headers['content-length'] = '20'; // bad length + next(); + }); - app.use(express.urlencoded()) + app.use(express.urlencoded()); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); request(app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('str=') - .expect(400, /content length/, done) - }) + .expect(400, /content length/, done); + }); it('should handle Content-Length: 0', function (done) { request(this.app) @@ -50,8 +49,8 @@ describe('express.urlencoded()', function () { .set('Content-Type', 'application/x-www-form-urlencoded') .set('Content-Length', '0') .send('') - .expect(200, '{}', done) - }) + .expect(200, '{}', done); + }); it('should handle empty message-body', function (done) { request(createApp({ limit: '1kb' })) @@ -59,107 +58,107 @@ describe('express.urlencoded()', function () { .set('Content-Type', 'application/x-www-form-urlencoded') .set('Transfer-Encoding', 'chunked') .send('') - .expect(200, '{}', done) - }) + .expect(200, '{}', done); + }); it('should handle duplicated middleware', function (done) { - var app = express() + var app = express(); - app.use(express.urlencoded()) - app.use(express.urlencoded()) + app.use(express.urlencoded()); + app.use(express.urlencoded()); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); request(app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user=tobi') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should not parse extended syntax', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user[name][first]=Tobi') - .expect(200, '{"user[name][first]":"Tobi"}', done) - }) + .expect(200, '{"user[name][first]":"Tobi"}', done); + }); describe('with extended option', function () { describe('when false', function () { before(function () { - this.app = createApp({ extended: false }) - }) + this.app = createApp({ extended: false }); + }); it('should not parse extended syntax', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user[name][first]=Tobi') - .expect(200, '{"user[name][first]":"Tobi"}', done) - }) + .expect(200, '{"user[name][first]":"Tobi"}', done); + }); it('should parse multiple key instances', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user=Tobi&user=Loki') - .expect(200, '{"user":["Tobi","Loki"]}', done) - }) - }) + .expect(200, '{"user":["Tobi","Loki"]}', done); + }); + }); describe('when true', function () { before(function () { - this.app = createApp({ extended: true }) - }) + this.app = createApp({ extended: true }); + }); it('should parse multiple key instances', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user=Tobi&user=Loki') - .expect(200, '{"user":["Tobi","Loki"]}', done) - }) + .expect(200, '{"user":["Tobi","Loki"]}', done); + }); it('should parse extended syntax', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user[name][first]=Tobi') - .expect(200, '{"user":{"name":{"first":"Tobi"}}}', done) - }) + .expect(200, '{"user":{"name":{"first":"Tobi"}}}', done); + }); it('should parse parameters with dots', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user.name=Tobi') - .expect(200, '{"user.name":"Tobi"}', done) - }) + .expect(200, '{"user.name":"Tobi"}', done); + }); it('should parse fully-encoded extended syntax', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user%5Bname%5D%5Bfirst%5D=Tobi') - .expect(200, '{"user":{"name":{"first":"Tobi"}}}', done) - }) + .expect(200, '{"user":{"name":{"first":"Tobi"}}}', done); + }); it('should parse array index notation', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('foo[0]=bar&foo[1]=baz') - .expect(200, '{"foo":["bar","baz"]}', done) - }) + .expect(200, '{"foo":["bar","baz"]}', done); + }); it('should parse array index notation with large array', function (done) { - var str = 'f[0]=0' + var str = 'f[0]=0'; for (var i = 1; i < 500; i++) { - str += '&f[' + i + ']=' + i.toString(16) + str += '&f[' + i + ']=' + i.toString(16); } request(this.app) @@ -167,174 +166,204 @@ describe('express.urlencoded()', function () { .set('Content-Type', 'application/x-www-form-urlencoded') .send(str) .expect(function (res) { - var obj = JSON.parse(res.text) - assert.strictEqual(Object.keys(obj).length, 1) - assert.strictEqual(Array.isArray(obj.f), true) - assert.strictEqual(obj.f.length, 500) + var obj = JSON.parse(res.text); + assert.strictEqual(Object.keys(obj).length, 1); + assert.strictEqual(Array.isArray(obj.f), true); + assert.strictEqual(obj.f.length, 500); }) - .expect(200, done) - }) + .expect(200, done); + }); it('should parse array of objects syntax', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!') - .expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done) - }) + .expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done); + }); it('should parse deep object', function (done) { - var str = 'foo' + var str = 'foo'; for (var i = 0; i < 32; i++) { - str += '[p]' + str += '[p]'; } - str += '=bar' + str += '=bar'; request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(str) .expect(function (res) { - var obj = JSON.parse(res.text) - assert.strictEqual(Object.keys(obj).length, 1) - assert.strictEqual(typeof obj.foo, 'object') - - var depth = 0 - var ref = obj.foo - while ((ref = ref.p)) { depth++ } - assert.strictEqual(depth, 32) + var obj = JSON.parse(res.text); + assert.strictEqual(Object.keys(obj).length, 1); + assert.strictEqual(typeof obj.foo, 'object'); + + var depth = 0; + var ref = obj.foo; + while ((ref = ref.p)) { + depth++; + } + assert.strictEqual(depth, 32); }) - .expect(200, done) - }) - }) - }) + .expect(200, done); + }); + }); + }); describe('with inflate option', function () { describe('when false', function () { before(function () { - this.app = createApp({ inflate: false }) - }) + this.app = createApp({ inflate: false }); + }); it('should not accept content-encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(415, '[encoding.unsupported] content encoding unsupported', done) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect( + 415, + '[encoding.unsupported] content encoding unsupported', + done, + ); + }); + }); describe('when true', function () { before(function () { - this.app = createApp({ inflate: true }) - }) + this.app = createApp({ inflate: true }); + }); it('should accept content-encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) - }) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect(200, '{"name":"论"}', done); + }); + }); + }); describe('with limit option', function () { it('should 413 when over limit with Content-Length', function (done) { - var buf = Buffer.alloc(1024, '.') + var buf = Buffer.alloc(1024, '.'); request(createApp({ limit: '1kb' })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .set('Content-Length', '1028') .send('str=' + buf.toString()) - .expect(413, done) - }) + .expect(413, done); + }); it('should 413 when over limit with chunked encoding', function (done) { - var app = createApp({ limit: '1kb' }) - var buf = Buffer.alloc(1024, '.') - var test = request(app).post('/') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.set('Transfer-Encoding', 'chunked') - test.write('str=') - test.write(buf.toString()) - test.expect(413, done) - }) + var app = createApp({ limit: '1kb' }); + var buf = Buffer.alloc(1024, '.'); + var test = request(app).post('/'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.set('Transfer-Encoding', 'chunked'); + test.write('str='); + test.write(buf.toString()); + test.expect(413, done); + }); it('should 413 when inflated body over limit', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f9204040000', 'hex')) - test.expect(413, done) - }) + var app = createApp({ limit: '1kb' }); + var test = request(app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write( + Buffer.from( + '1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f9204040000', + 'hex', + ), + ); + test.expect(413, done); + }); it('should accept number of bytes', function (done) { - var buf = Buffer.alloc(1024, '.') + var buf = Buffer.alloc(1024, '.'); request(createApp({ limit: 1024 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('str=' + buf.toString()) - .expect(413, done) - }) + .expect(413, done); + }); it('should not change when options altered', function (done) { - var buf = Buffer.alloc(1024, '.') - var options = { limit: '1kb' } - var app = createApp(options) + var buf = Buffer.alloc(1024, '.'); + var options = { limit: '1kb' }; + var app = createApp(options); - options.limit = '100kb' + options.limit = '100kb'; request(app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('str=' + buf.toString()) - .expect(413, done) - }) + .expect(413, done); + }); it('should not hang response', function (done) { - var app = createApp({ limit: '8kb' }) - var buf = Buffer.alloc(10240, '.') - var test = request(app).post('/') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(buf) - test.write(buf) - test.write(buf) - test.expect(413, done) - }) + var app = createApp({ limit: '8kb' }); + var buf = Buffer.alloc(10240, '.'); + var test = request(app).post('/'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write(buf); + test.write(buf); + test.write(buf); + test.expect(413, done); + }); it('should not error when inflating', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f92040400', 'hex')) - test.expect(413, done) - }) - }) + var app = createApp({ limit: '1kb' }); + var test = request(app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write( + Buffer.from( + '1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f92040400', + 'hex', + ), + ); + test.expect(413, done); + }); + }); describe('with parameterLimit option', function () { describe('with extended: false', function () { it('should reject 0', function () { - assert.throws(createApp.bind(null, { extended: false, parameterLimit: 0 }), - /TypeError: option parameterLimit must be a positive number/) - }) + assert.throws( + createApp.bind(null, { extended: false, parameterLimit: 0 }), + /TypeError: option parameterLimit must be a positive number/, + ); + }); it('should reject string', function () { - assert.throws(createApp.bind(null, { extended: false, parameterLimit: 'beep' }), - /TypeError: option parameterLimit must be a positive number/) - }) + assert.throws( + createApp.bind(null, { extended: false, parameterLimit: 'beep' }), + /TypeError: option parameterLimit must be a positive number/, + ); + }); it('should 413 if over limit', function (done) { request(createApp({ extended: false, parameterLimit: 10 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(11)) - .expect(413, '[parameters.too.many] too many parameters', done) - }) + .expect(413, '[parameters.too.many] too many parameters', done); + }); it('should work when at the limit', function (done) { request(createApp({ extended: false, parameterLimit: 10 })) @@ -342,16 +371,16 @@ describe('express.urlencoded()', function () { .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(10)) .expect(expectKeyCount(10)) - .expect(200, done) - }) + .expect(200, done); + }); it('should work if number is floating point', function (done) { request(createApp({ extended: false, parameterLimit: 10.1 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(11)) - .expect(413, /too many parameters/, done) - }) + .expect(413, /too many parameters/, done); + }); it('should work with large limit', function (done) { request(createApp({ extended: false, parameterLimit: 5000 })) @@ -359,8 +388,8 @@ describe('express.urlencoded()', function () { .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(5000)) .expect(expectKeyCount(5000)) - .expect(200, done) - }) + .expect(200, done); + }); it('should work with Infinity limit', function (done) { request(createApp({ extended: false, parameterLimit: Infinity })) @@ -368,28 +397,32 @@ describe('express.urlencoded()', function () { .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(10000)) .expect(expectKeyCount(10000)) - .expect(200, done) - }) - }) + .expect(200, done); + }); + }); describe('with extended: true', function () { it('should reject 0', function () { - assert.throws(createApp.bind(null, { extended: true, parameterLimit: 0 }), - /TypeError: option parameterLimit must be a positive number/) - }) + assert.throws( + createApp.bind(null, { extended: true, parameterLimit: 0 }), + /TypeError: option parameterLimit must be a positive number/, + ); + }); it('should reject string', function () { - assert.throws(createApp.bind(null, { extended: true, parameterLimit: 'beep' }), - /TypeError: option parameterLimit must be a positive number/) - }) + assert.throws( + createApp.bind(null, { extended: true, parameterLimit: 'beep' }), + /TypeError: option parameterLimit must be a positive number/, + ); + }); it('should 413 if over limit', function (done) { request(createApp({ extended: true, parameterLimit: 10 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(11)) - .expect(413, '[parameters.too.many] too many parameters', done) - }) + .expect(413, '[parameters.too.many] too many parameters', done); + }); it('should work when at the limit', function (done) { request(createApp({ extended: true, parameterLimit: 10 })) @@ -397,16 +430,16 @@ describe('express.urlencoded()', function () { .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(10)) .expect(expectKeyCount(10)) - .expect(200, done) - }) + .expect(200, done); + }); it('should work if number is floating point', function (done) { request(createApp({ extended: true, parameterLimit: 10.1 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(11)) - .expect(413, /too many parameters/, done) - }) + .expect(413, /too many parameters/, done); + }); it('should work with large limit', function (done) { request(createApp({ extended: true, parameterLimit: 5000 })) @@ -414,8 +447,8 @@ describe('express.urlencoded()', function () { .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(5000)) .expect(expectKeyCount(5000)) - .expect(200, done) - }) + .expect(200, done); + }); it('should work with Infinity limit', function (done) { request(createApp({ extended: true, parameterLimit: Infinity })) @@ -423,228 +456,235 @@ describe('express.urlencoded()', function () { .set('Content-Type', 'application/x-www-form-urlencoded') .send(createManyParams(10000)) .expect(expectKeyCount(10000)) - .expect(200, done) - }) - }) - }) + .expect(200, done); + }); + }); + }); describe('with type option', function () { describe('when "application/vnd.x-www-form-urlencoded"', function () { before(function () { - this.app = createApp({ type: 'application/vnd.x-www-form-urlencoded' }) - }) + this.app = createApp({ type: 'application/vnd.x-www-form-urlencoded' }); + }); it('should parse for custom type', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/vnd.x-www-form-urlencoded') .send('user=tobi') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should ignore standard type', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user=tobi') - .expect(200, '', done) - }) - }) + .expect(200, '', done); + }); + }); describe('when ["urlencoded", "application/x-pairs"]', function () { before(function () { this.app = createApp({ - type: ['urlencoded', 'application/x-pairs'] - }) - }) + type: ['urlencoded', 'application/x-pairs'], + }); + }); it('should parse "application/x-www-form-urlencoded"', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user=tobi') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should parse "application/x-pairs"', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-pairs') .send('user=tobi') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should ignore application/x-foo', function (done) { request(this.app) .post('/') .set('Content-Type', 'application/x-foo') .send('user=tobi') - .expect(200, '', done) - }) - }) + .expect(200, '', done); + }); + }); describe('when a function', function () { it('should parse when truthy value returned', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - return req.headers['content-type'] === 'application/vnd.something' + function accept(req) { + return req.headers['content-type'] === 'application/vnd.something'; } request(app) .post('/') .set('Content-Type', 'application/vnd.something') .send('user=tobi') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should work without content-type', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - return true + function accept(req) { + return true; } - var test = request(app).post('/') - test.write('user=tobi') - test.expect(200, '{"user":"tobi"}', done) - }) + var test = request(app).post('/'); + test.write('user=tobi'); + test.expect(200, '{"user":"tobi"}', done); + }); it('should not invoke without a body', function (done) { - var app = createApp({ type: accept }) + var app = createApp({ type: accept }); - function accept (req) { - throw new Error('oops!') + function accept(req) { + throw new Error('oops!'); } - request(app) - .get('/') - .expect(404, done) - }) - }) - }) + request(app).get('/').expect(404, done); + }); + }); + }); describe('with verify option', function () { it('should assert value if function', function () { - assert.throws(createApp.bind(null, { verify: 'lol' }), - /TypeError: option verify must be function/) - }) + assert.throws( + createApp.bind(null, { verify: 'lol' }), + /TypeError: option verify must be function/, + ); + }); it('should error from verify', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x20) throw new Error('no leading space') - } - }) + if (buf[0] === 0x20) throw new Error('no leading space'); + }, + }); request(app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(' user=tobi') - .expect(403, '[entity.verify.failed] no leading space', done) - }) + .expect(403, '[entity.verify.failed] no leading space', done); + }); it('should allow custom codes', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] !== 0x20) return - var err = new Error('no leading space') - err.status = 400 - throw err - } - }) + if (buf[0] !== 0x20) return; + var err = new Error('no leading space'); + err.status = 400; + throw err; + }, + }); request(app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(' user=tobi') - .expect(400, '[entity.verify.failed] no leading space', done) - }) + .expect(400, '[entity.verify.failed] no leading space', done); + }); it('should allow custom type', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] !== 0x20) return - var err = new Error('no leading space') - err.type = 'foo.bar' - throw err - } - }) + if (buf[0] !== 0x20) return; + var err = new Error('no leading space'); + err.type = 'foo.bar'; + throw err; + }, + }); request(app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(' user=tobi') - .expect(403, '[foo.bar] no leading space', done) - }) + .expect(403, '[foo.bar] no leading space', done); + }); it('should allow pass-through', function (done) { var app = createApp({ verify: function (req, res, buf) { - if (buf[0] === 0x5b) throw new Error('no arrays') - } - }) + if (buf[0] === 0x5b) throw new Error('no arrays'); + }, + }); request(app) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send('user=tobi') - .expect(200, '{"user":"tobi"}', done) - }) + .expect(200, '{"user":"tobi"}', done); + }); it('should 415 on unknown charset prior to verify', function (done) { var app = createApp({ verify: function (req, res, buf) { - throw new Error('unexpected verify call') - } - }) - - var test = request(app).post('/') - test.set('Content-Type', 'application/x-www-form-urlencoded; charset=x-bogus') - test.write(Buffer.from('00000000', 'hex')) - test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done) - }) - }) + throw new Error('unexpected verify call'); + }, + }); + + var test = request(app).post('/'); + test.set( + 'Content-Type', + 'application/x-www-form-urlencoded; charset=x-bogus', + ); + test.write(Buffer.from('00000000', 'hex')); + test.expect( + 415, + '[charset.unsupported] unsupported charset "X-BOGUS"', + done, + ); + }); + }); describeAsyncHooks('async local storage', function () { before(function () { - var app = express() - var store = { foo: 'bar' } + var app = express(); + var store = { foo: 'bar' }; app.use(function (req, res, next) { - req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage() - req.asyncLocalStorage.run(store, next) - }) + req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage(); + req.asyncLocalStorage.run(store, next); + }); - app.use(express.urlencoded()) + app.use(express.urlencoded()); app.use(function (req, res, next) { - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); if (local) { - res.setHeader('x-store-foo', String(local.foo)) + res.setHeader('x-store-foo', String(local.foo)); } - next() - }) + next(); + }); app.use(function (err, req, res, next) { - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); if (local) { - res.setHeader('x-store-foo', String(local.foo)) + res.setHeader('x-store-foo', String(local.foo)); } - res.status(err.status || 500) - res.send('[' + err.type + '] ' + err.message) - }) + res.status(err.status || 500); + res.send('[' + err.type + '] ' + err.message); + }); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); - this.app = app - }) + this.app = app; + }); it('should presist store', function (done) { request(this.app) @@ -654,8 +694,8 @@ describe('express.urlencoded()', function () { .expect(200) .expect('x-store-foo', 'bar') .expect('{"user":"tobi"}') - .end(done) - }) + .end(done); + }); it('should presist store when unmatched content-type', function (done) { request(this.app) @@ -664,29 +704,39 @@ describe('express.urlencoded()', function () { .send('buzz') .expect(200) .expect('x-store-foo', 'bar') - .end(done) - }) + .end(done); + }); it('should presist store when inflated', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(200) - test.expect('x-store-foo', 'bar') - test.expect('{"name":"论"}') - test.end(done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect(200); + test.expect('x-store-foo', 'bar'); + test.expect('{"name":"论"}'); + test.end(done); + }); it('should presist store when inflate error', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', 'hex')) - test.expect(400) - test.expect('x-store-foo', 'bar') - test.end(done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', + 'hex', + ), + ); + test.expect(400); + test.expect('x-store-foo', 'bar'); + test.end(done); + }); it('should presist store when limit exceeded', function (done) { request(this.app) @@ -695,145 +745,176 @@ describe('express.urlencoded()', function () { .send('user=' + Buffer.alloc(1024 * 100, '.').toString()) .expect(413) .expect('x-store-foo', 'bar') - .end(done) - }) - }) + .end(done); + }); + }); describe('charset', function () { before(function () { - this.app = createApp() - }) + this.app = createApp(); + }); it('should parse utf-8', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8') - test.write(Buffer.from('6e616d653de8aeba', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set( + 'Content-Type', + 'application/x-www-form-urlencoded; charset=utf-8', + ); + test.write(Buffer.from('6e616d653de8aeba', 'hex')); + test.expect(200, '{"name":"论"}', done); + }); it('should parse when content-length != char length', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8') - test.set('Content-Length', '7') - test.write(Buffer.from('746573743dc3a5', 'hex')) - test.expect(200, '{"test":"å"}', done) - }) + var test = request(this.app).post('/'); + test.set( + 'Content-Type', + 'application/x-www-form-urlencoded; charset=utf-8', + ); + test.set('Content-Length', '7'); + test.write(Buffer.from('746573743dc3a5', 'hex')); + test.expect(200, '{"test":"å"}', done); + }); it('should default to utf-8', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('6e616d653de8aeba', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write(Buffer.from('6e616d653de8aeba', 'hex')); + test.expect(200, '{"name":"论"}', done); + }); it('should fail on unknown charset', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/x-www-form-urlencoded; charset=koi8-r') - test.write(Buffer.from('6e616d653dcec5d4', 'hex')) - test.expect(415, '[charset.unsupported] unsupported charset "KOI8-R"', done) - }) - }) + var test = request(this.app).post('/'); + test.set( + 'Content-Type', + 'application/x-www-form-urlencoded; charset=koi8-r', + ); + test.write(Buffer.from('6e616d653dcec5d4', 'hex')); + test.expect( + 415, + '[charset.unsupported] unsupported charset "KOI8-R"', + done, + ); + }); + }); describe('encoding', function () { before(function () { - this.app = createApp({ limit: '10kb' }) - }) + this.app = createApp({ limit: '10kb' }); + }); it('should parse without encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('6e616d653de8aeba', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write(Buffer.from('6e616d653de8aeba', 'hex')); + test.expect(200, '{"name":"论"}', done); + }); it('should support identity encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'identity') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('6e616d653de8aeba', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'identity'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write(Buffer.from('6e616d653de8aeba', 'hex')); + test.expect(200, '{"name":"论"}', done); + }); it('should support gzip encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'gzip') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'gzip'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect(200, '{"name":"论"}', done); + }); it('should support deflate encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'deflate') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'deflate'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex')); + test.expect(200, '{"name":"论"}', done); + }); it('should be case-insensitive', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'GZIP') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) - test.expect(200, '{"name":"论"}', done) - }) + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'GZIP'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write( + Buffer.from( + '1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', + 'hex', + ), + ); + test.expect(200, '{"name":"论"}', done); + }); it('should 415 on unknown encoding', function (done) { - var test = request(this.app).post('/') - test.set('Content-Encoding', 'nulls') - test.set('Content-Type', 'application/x-www-form-urlencoded') - test.write(Buffer.from('000000000000', 'hex')) - test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done) - }) - }) -}) - -function createManyParams (count) { - var str = '' + var test = request(this.app).post('/'); + test.set('Content-Encoding', 'nulls'); + test.set('Content-Type', 'application/x-www-form-urlencoded'); + test.write(Buffer.from('000000000000', 'hex')); + test.expect( + 415, + '[encoding.unsupported] unsupported content encoding "nulls"', + done, + ); + }); + }); +}); + +function createManyParams(count) { + var str = ''; if (count === 0) { - return str + return str; } - str += '0=0' + str += '0=0'; for (var i = 1; i < count; i++) { - var n = i.toString(36) - str += '&' + n + '=' + n + var n = i.toString(36); + str += '&' + n + '=' + n; } - return str + return str; } -function createApp (options) { - var app = express() +function createApp(options) { + var app = express(); - app.use(express.urlencoded(options)) + app.use(express.urlencoded(options)); app.use(function (err, req, res, next) { - res.status(err.status || 500) - res.send(String(req.headers['x-error-property'] - ? err[req.headers['x-error-property']] - : ('[' + err.type + '] ' + err.message))) - }) + res.status(err.status || 500); + res.send( + String( + req.headers['x-error-property'] + ? err[req.headers['x-error-property']] + : '[' + err.type + '] ' + err.message, + ), + ); + }); app.post('/', function (req, res) { - res.json(req.body) - }) + res.json(req.body); + }); - return app + return app; } -function expectKeyCount (count) { +function expectKeyCount(count) { return function (res) { - assert.strictEqual(Object.keys(JSON.parse(res.text)).length, count) - } + assert.strictEqual(Object.keys(JSON.parse(res.text)).length, count); + }; } -function tryRequire (name) { +function tryRequire(name) { try { - return require(name) + return require(name); } catch (e) { - return {} + return {}; } } diff --git a/test/middleware.basic.js b/test/middleware.basic.js index 19f00d9a296..c533d2e5770 100644 --- a/test/middleware.basic.js +++ b/test/middleware.basic.js @@ -1,42 +1,46 @@ -'use strict' +'use strict'; -var assert = require('assert') +var assert = require('assert'); var express = require('../'); var request = require('supertest'); -describe('middleware', function(){ - describe('.next()', function(){ - it('should behave like connect', function(done){ - var app = express() - , calls = []; +describe('middleware', function () { + describe('.next()', function () { + it('should behave like connect', function (done) { + var app = express(), + calls = []; - app.use(function(req, res, next){ + app.use(function (req, res, next) { calls.push('one'); next(); }); - app.use(function(req, res, next){ + app.use(function (req, res, next) { calls.push('two'); next(); }); - app.use(function(req, res){ + app.use(function (req, res) { var buf = ''; res.setHeader('Content-Type', 'application/json'); req.setEncoding('utf8'); - req.on('data', function(chunk){ buf += chunk }); - req.on('end', function(){ + req.on('data', function (chunk) { + buf += chunk; + }); + req.on('end', function () { res.end(buf); }); }); request(app) - .get('/') - .set('Content-Type', 'application/json') - .send('{"foo":"bar"}') - .expect('Content-Type', 'application/json') - .expect(function () { assert.deepEqual(calls, ['one', 'two']) }) - .expect(200, '{"foo":"bar"}', done) - }) - }) -}) + .get('/') + .set('Content-Type', 'application/json') + .send('{"foo":"bar"}') + .expect('Content-Type', 'application/json') + .expect(function () { + assert.deepEqual(calls, ['one', 'two']); + }) + .expect(200, '{"foo":"bar"}', done); + }); + }); +}); diff --git a/test/regression.js b/test/regression.js index 4e99b306948..79e16f6a7d3 100644 --- a/test/regression.js +++ b/test/regression.js @@ -1,20 +1,17 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('throw after .end()', function(){ - it('should fail gracefully', function(done){ +describe('throw after .end()', function () { + it('should fail gracefully', function (done) { var app = express(); - app.get('/', function(req, res){ + app.get('/', function (req, res) { res.end('yay'); throw new Error('boom'); }); - request(app) - .get('/') - .expect('yay') - .expect(200, done); - }) -}) + request(app).get('/').expect('yay').expect(200, done); + }); +}); diff --git a/test/req.accepts.js b/test/req.accepts.js index 2066fb51859..640cf693dcf 100644 --- a/test/req.accepts.js +++ b/test/req.accepts.js @@ -1,125 +1,114 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.accepts(type)', function(){ - it('should return true when Accept is not present', function(done){ +describe('req', function () { + describe('.accepts(type)', function () { + it('should return true when Accept is not present', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.accepts('json') ? 'yes' : 'no'); }); - request(app) - .get('/') - .expect('yes', done); - }) + request(app).get('/').expect('yes', done); + }); - it('should return true when present', function(done){ + it('should return true when present', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.accepts('json') ? 'yes' : 'no'); }); request(app) - .get('/') - .set('Accept', 'application/json') - .expect('yes', done); - }) + .get('/') + .set('Accept', 'application/json') + .expect('yes', done); + }); - it('should return false otherwise', function(done){ + it('should return false otherwise', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.accepts('json') ? 'yes' : 'no'); }); - request(app) - .get('/') - .set('Accept', 'text/html') - .expect('no', done); - }) - }) + request(app).get('/').set('Accept', 'text/html').expect('no', done); + }); + }); - it('should accept an argument list of type names', function(done){ + it('should accept an argument list of type names', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.accepts('json', 'html')); }); request(app) - .get('/') - .set('Accept', 'application/json') - .expect('json', done); - }) + .get('/') + .set('Accept', 'application/json') + .expect('json', done); + }); - describe('.accepts(types)', function(){ - it('should return the first when Accept is not present', function(done){ + describe('.accepts(types)', function () { + it('should return the first when Accept is not present', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.accepts(['json', 'html'])); }); - request(app) - .get('/') - .expect('json', done); - }) + request(app).get('/').expect('json', done); + }); - it('should return the first acceptable type', function(done){ + it('should return the first acceptable type', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.accepts(['json', 'html'])); }); - request(app) - .get('/') - .set('Accept', 'text/html') - .expect('html', done); - }) + request(app).get('/').set('Accept', 'text/html').expect('html', done); + }); - it('should return false when no match is made', function(done){ + it('should return false when no match is made', function (done) { var app = express(); - app.use(function(req, res, next){ - res.end(req.accepts(['text/html', 'application/json']) ? 'yup' : 'nope'); + app.use(function (req, res, next) { + res.end( + req.accepts(['text/html', 'application/json']) ? 'yup' : 'nope', + ); }); request(app) - .get('/') - .set('Accept', 'foo/bar, bar/baz') - .expect('nope', done); - }) + .get('/') + .set('Accept', 'foo/bar, bar/baz') + .expect('nope', done); + }); - it('should take quality into account', function(done){ + it('should take quality into account', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.accepts(['text/html', 'application/json'])); }); request(app) - .get('/') - .set('Accept', '*/html; q=.5, application/json') - .expect('application/json', done); - }) + .get('/') + .set('Accept', '*/html; q=.5, application/json') + .expect('application/json', done); + }); - it('should return the first acceptable type with canonical mime types', function(done){ + it('should return the first acceptable type with canonical mime types', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.accepts(['application/json', 'text/html'])); }); - request(app) - .get('/') - .set('Accept', '*/html') - .expect('text/html', done); - }) - }) -}) + request(app).get('/').set('Accept', '*/html').expect('text/html', done); + }); + }); +}); diff --git a/test/req.acceptsCharsets.js b/test/req.acceptsCharsets.js index 360a9878a78..0bb174fd074 100644 --- a/test/req.acceptsCharsets.js +++ b/test/req.acceptsCharsets.js @@ -1,50 +1,48 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.acceptsCharsets(type)', function(){ - describe('when Accept-Charset is not present', function(){ - it('should return true', function(done){ +describe('req', function () { + describe('.acceptsCharsets(type)', function () { + describe('when Accept-Charset is not present', function () { + it('should return true', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no'); }); - request(app) - .get('/') - .expect('yes', done); - }) - }) + request(app).get('/').expect('yes', done); + }); + }); describe('when Accept-Charset is present', function () { it('should return true', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no'); }); request(app) - .get('/') - .set('Accept-Charset', 'foo, bar, utf-8') - .expect('yes', done); - }) + .get('/') + .set('Accept-Charset', 'foo, bar, utf-8') + .expect('yes', done); + }); - it('should return false otherwise', function(done){ + it('should return false otherwise', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no'); }); request(app) - .get('/') - .set('Accept-Charset', 'foo, bar') - .expect('no', done); - }) - }) - }) -}) + .get('/') + .set('Accept-Charset', 'foo, bar') + .expect('no', done); + }); + }); + }); +}); diff --git a/test/req.acceptsEncodings.js b/test/req.acceptsEncodings.js index 9f8973cdfb8..931fcb7454d 100644 --- a/test/req.acceptsEncodings.js +++ b/test/req.acceptsEncodings.js @@ -1,9 +1,9 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ +describe('req', function () { describe('.acceptsEncodings', function () { it('should return encoding if accepted', function (done) { var app = express(); @@ -11,29 +11,29 @@ describe('req', function(){ app.get('/', function (req, res) { res.send({ gzip: req.acceptsEncodings('gzip'), - deflate: req.acceptsEncodings('deflate') - }) - }) + deflate: req.acceptsEncodings('deflate'), + }); + }); request(app) .get('/') .set('Accept-Encoding', ' gzip, deflate') - .expect(200, { gzip: 'gzip', deflate: 'deflate' }, done) - }) + .expect(200, { gzip: 'gzip', deflate: 'deflate' }, done); + }); - it('should be false if encoding not accepted', function(done){ + it('should be false if encoding not accepted', function (done) { var app = express(); app.get('/', function (req, res) { res.send({ - bogus: req.acceptsEncodings('bogus') - }) - }) + bogus: req.acceptsEncodings('bogus'), + }); + }); request(app) .get('/') .set('Accept-Encoding', ' gzip, deflate') - .expect(200, { bogus: false }, done) - }) - }) -}) + .expect(200, { bogus: false }, done); + }); + }); +}); diff --git a/test/req.acceptsLanguages.js b/test/req.acceptsLanguages.js index e5629fbc323..5993b696bf9 100644 --- a/test/req.acceptsLanguages.js +++ b/test/req.acceptsLanguages.js @@ -1,42 +1,42 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.acceptsLanguages', function(){ +describe('req', function () { + describe('.acceptsLanguages', function () { it('should return language if accepted', function (done) { var app = express(); app.get('/', function (req, res) { res.send({ 'en-us': req.acceptsLanguages('en-us'), - en: req.acceptsLanguages('en') - }) - }) + en: req.acceptsLanguages('en'), + }); + }); request(app) .get('/') .set('Accept-Language', 'en;q=.5, en-us') - .expect(200, { 'en-us': 'en-us', en: 'en' }, done) - }) + .expect(200, { 'en-us': 'en-us', en: 'en' }, done); + }); - it('should be false if language not accepted', function(done){ + it('should be false if language not accepted', function (done) { var app = express(); app.get('/', function (req, res) { res.send({ - es: req.acceptsLanguages('es') - }) - }) + es: req.acceptsLanguages('es'), + }); + }); request(app) .get('/') .set('Accept-Language', 'en;q=.5, en-us') - .expect(200, { es: false }, done) - }) + .expect(200, { es: false }, done); + }); - describe('when Accept-Language is not present', function(){ + describe('when Accept-Language is not present', function () { it('should always return language', function (done) { var app = express(); @@ -44,14 +44,14 @@ describe('req', function(){ res.send({ en: req.acceptsLanguages('en'), es: req.acceptsLanguages('es'), - jp: req.acceptsLanguages('jp') - }) - }) + jp: req.acceptsLanguages('jp'), + }); + }); request(app) .get('/') - .expect(200, { en: 'en', es: 'es', jp: 'jp' }, done) - }) - }) - }) -}) + .expect(200, { en: 'en', es: 'es', jp: 'jp' }, done); + }); + }); + }); +}); diff --git a/test/req.baseUrl.js b/test/req.baseUrl.js index b70803ea8bb..3823cd8e876 100644 --- a/test/req.baseUrl.js +++ b/test/req.baseUrl.js @@ -1,88 +1,82 @@ -'use strict' +'use strict'; -var express = require('..') -var request = require('supertest') +var express = require('..'); +var request = require('supertest'); -describe('req', function(){ - describe('.baseUrl', function(){ - it('should be empty for top-level route', function(done){ - var app = express() +describe('req', function () { + describe('.baseUrl', function () { + it('should be empty for top-level route', function (done) { + var app = express(); - app.get('/:a', function(req, res){ - res.end(req.baseUrl) - }) + app.get('/:a', function (req, res) { + res.end(req.baseUrl); + }); - request(app) - .get('/foo') - .expect(200, '', done) - }) + request(app).get('/foo').expect(200, '', done); + }); - it('should contain lower path', function(done){ - var app = express() - var sub = express.Router() + it('should contain lower path', function (done) { + var app = express(); + var sub = express.Router(); - sub.get('/:b', function(req, res){ - res.end(req.baseUrl) - }) - app.use('/:a', sub) + sub.get('/:b', function (req, res) { + res.end(req.baseUrl); + }); + app.use('/:a', sub); - request(app) - .get('/foo/bar') - .expect(200, '/foo', done); - }) + request(app).get('/foo/bar').expect(200, '/foo', done); + }); - it('should contain full lower path', function(done){ - var app = express() - var sub1 = express.Router() - var sub2 = express.Router() - var sub3 = express.Router() + it('should contain full lower path', function (done) { + var app = express(); + var sub1 = express.Router(); + var sub2 = express.Router(); + var sub3 = express.Router(); - sub3.get('/:d', function(req, res){ - res.end(req.baseUrl) - }) - sub2.use('/:c', sub3) - sub1.use('/:b', sub2) - app.use('/:a', sub1) + sub3.get('/:d', function (req, res) { + res.end(req.baseUrl); + }); + sub2.use('/:c', sub3); + sub1.use('/:b', sub2); + app.use('/:a', sub1); - request(app) - .get('/foo/bar/baz/zed') - .expect(200, '/foo/bar/baz', done); - }) + request(app).get('/foo/bar/baz/zed').expect(200, '/foo/bar/baz', done); + }); - it('should travel through routers correctly', function(done){ - var urls = [] - var app = express() - var sub1 = express.Router() - var sub2 = express.Router() - var sub3 = express.Router() + it('should travel through routers correctly', function (done) { + var urls = []; + var app = express(); + var sub1 = express.Router(); + var sub2 = express.Router(); + var sub3 = express.Router(); - sub3.get('/:d', function(req, res, next){ - urls.push('0@' + req.baseUrl) - next() - }) - sub2.use('/:c', sub3) - sub1.use('/', function(req, res, next){ - urls.push('1@' + req.baseUrl) - next() - }) - sub1.use('/bar', sub2) - sub1.use('/bar', function(req, res, next){ - urls.push('2@' + req.baseUrl) - next() - }) - app.use(function(req, res, next){ - urls.push('3@' + req.baseUrl) - next() - }) - app.use('/:a', sub1) - app.use(function(req, res, next){ - urls.push('4@' + req.baseUrl) - res.end(urls.join(',')) - }) + sub3.get('/:d', function (req, res, next) { + urls.push('0@' + req.baseUrl); + next(); + }); + sub2.use('/:c', sub3); + sub1.use('/', function (req, res, next) { + urls.push('1@' + req.baseUrl); + next(); + }); + sub1.use('/bar', sub2); + sub1.use('/bar', function (req, res, next) { + urls.push('2@' + req.baseUrl); + next(); + }); + app.use(function (req, res, next) { + urls.push('3@' + req.baseUrl); + next(); + }); + app.use('/:a', sub1); + app.use(function (req, res, next) { + urls.push('4@' + req.baseUrl); + res.end(urls.join(',')); + }); request(app) - .get('/foo/bar/baz/zed') - .expect(200, '3@,1@/foo,0@/foo/bar/baz,2@/foo/bar,4@', done); - }) - }) -}) + .get('/foo/bar/baz/zed') + .expect(200, '3@,1@/foo,0@/foo/bar/baz,2@/foo/bar,4@', done); + }); + }); +}); diff --git a/test/req.fresh.js b/test/req.fresh.js index 3bf6a1f65a7..bea8954a1a2 100644 --- a/test/req.fresh.js +++ b/test/req.fresh.js @@ -1,61 +1,56 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.fresh', function(){ - it('should return true when the resource is not modified', function(done){ +describe('req', function () { + describe('.fresh', function () { + it('should return true when the resource is not modified', function (done) { var app = express(); var etag = '"12345"'; - app.use(function(req, res){ + app.use(function (req, res) { res.set('ETag', etag); res.send(req.fresh); }); - request(app) - .get('/') - .set('If-None-Match', etag) - .expect(304, done); - }) + request(app).get('/').set('If-None-Match', etag).expect(304, done); + }); - it('should return false when the resource is modified', function(done){ + it('should return false when the resource is modified', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.set('ETag', '"123"'); res.send(req.fresh); }); request(app) - .get('/') - .set('If-None-Match', '"12345"') - .expect(200, 'false', done); - }) + .get('/') + .set('If-None-Match', '"12345"') + .expect(200, 'false', done); + }); - it('should return false without response headers', function(done){ + it('should return false without response headers', function (done) { var app = express(); - app.disable('x-powered-by') - app.use(function(req, res){ + app.disable('x-powered-by'); + app.use(function (req, res) { res.send(req.fresh); }); - request(app) - .get('/') - .expect(200, 'false', done); - }) + request(app).get('/').expect(200, 'false', done); + }); - it('should ignore "If-Modified-Since" when "If-None-Match" is present', function(done) { + it('should ignore "If-Modified-Since" when "If-None-Match" is present', function (done) { var app = express(); - const etag = '"FooBar"' - const now = Date.now() + const etag = '"FooBar"'; + const now = Date.now(); - app.disable('x-powered-by') - app.use(function(req, res) { - res.set('Etag', etag) - res.set('Last-Modified', new Date(now).toUTCString()) + app.disable('x-powered-by'); + app.use(function (req, res) { + res.set('Etag', etag); + res.set('Last-Modified', new Date(now).toUTCString()); res.send(req.fresh); }); @@ -64,7 +59,6 @@ describe('req', function(){ .set('If-Modified-Since', new Date(now - 1000).toUTCString) .set('If-None-Match', etag) .expect(304, done); - }) - - }) -}) + }); + }); +}); diff --git a/test/req.get.js b/test/req.get.js index 16589b3f059..cd38098b7a9 100644 --- a/test/req.get.js +++ b/test/req.get.js @@ -1,60 +1,60 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest') - , assert = require('assert'); +var express = require('../'), + request = require('supertest'), + assert = require('assert'); -describe('req', function(){ - describe('.get(field)', function(){ - it('should return the header field value', function(done){ +describe('req', function () { + describe('.get(field)', function () { + it('should return the header field value', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { assert(req.get('Something-Else') === undefined); res.end(req.get('Content-Type')); }); request(app) - .post('/') - .set('Content-Type', 'application/json') - .expect('application/json', done); - }) + .post('/') + .set('Content-Type', 'application/json') + .expect('application/json', done); + }); - it('should special-case Referer', function(done){ + it('should special-case Referer', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.get('Referer')); }); request(app) - .post('/') - .set('Referrer', 'http://foobar.com') - .expect('http://foobar.com', done); - }) + .post('/') + .set('Referrer', 'http://foobar.com') + .expect('http://foobar.com', done); + }); it('should throw missing header name', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.end(req.get()) - }) + res.end(req.get()); + }); request(app) - .get('/') - .expect(500, /TypeError: name argument is required to req.get/, done) - }) + .get('/') + .expect(500, /TypeError: name argument is required to req.get/, done); + }); it('should throw for non-string header name', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.end(req.get(42)) - }) + res.end(req.get(42)); + }); request(app) - .get('/') - .expect(500, /TypeError: name must be a string to req.get/, done) - }) - }) -}) + .get('/') + .expect(500, /TypeError: name must be a string to req.get/, done); + }); + }); +}); diff --git a/test/req.host.js b/test/req.host.js index cdda82eaae3..21e2abd1541 100644 --- a/test/req.host.js +++ b/test/req.host.js @@ -1,122 +1,117 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest') +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.host', function(){ - it('should return the Host when present', function(done){ +describe('req', function () { + describe('.host', function () { + it('should return the Host when present', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.host); }); request(app) - .post('/') - .set('Host', 'example.com') - .expect('example.com', done); - }) + .post('/') + .set('Host', 'example.com') + .expect('example.com', done); + }); - it('should strip port number', function(done){ + it('should strip port number', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.host); }); request(app) - .post('/') - .set('Host', 'example.com:3000') - .expect(200, 'example.com:3000', done); - }) + .post('/') + .set('Host', 'example.com:3000') + .expect(200, 'example.com:3000', done); + }); - it('should return undefined otherwise', function(done){ + it('should return undefined otherwise', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { req.headers.host = null; res.end(String(req.host)); }); - request(app) - .post('/') - .expect('undefined', done); - }) + request(app).post('/').expect('undefined', done); + }); - it('should work with IPv6 Host', function(done){ + it('should work with IPv6 Host', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.host); }); - request(app) - .post('/') - .set('Host', '[::1]') - .expect('[::1]', done); - }) + request(app).post('/').set('Host', '[::1]').expect('[::1]', done); + }); - it('should work with IPv6 Host and port', function(done){ + it('should work with IPv6 Host and port', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.host); }); request(app) - .post('/') - .set('Host', '[::1]:3000') - .expect(200, '[::1]:3000', done); - }) + .post('/') + .set('Host', '[::1]:3000') + .expect(200, '[::1]:3000', done); + }); - describe('when "trust proxy" is enabled', function(){ - it('should respect X-Forwarded-Host', function(done){ + describe('when "trust proxy" is enabled', function () { + it('should respect X-Forwarded-Host', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.host); }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com') - .expect('example.com', done); - }) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com') + .expect('example.com', done); + }); - it('should ignore X-Forwarded-Host if socket addr not trusted', function(done){ + it('should ignore X-Forwarded-Host if socket addr not trusted', function (done) { var app = express(); app.set('trust proxy', '10.0.0.1'); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.host); }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com') - .expect('localhost', done); - }) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com') + .expect('localhost', done); + }); - it('should default to Host', function(done){ + it('should default to Host', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.host); }); request(app) - .get('/') - .set('Host', 'example.com') - .expect('example.com', done); - }) + .get('/') + .set('Host', 'example.com') + .expect('example.com', done); + }); describe('when trusting hop count', function () { it('should respect X-Forwarded-Host', function (done) { @@ -129,28 +124,28 @@ describe('req', function(){ }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com') - .expect('example.com', done); - }) - }) - }) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com') + .expect('example.com', done); + }); + }); + }); - describe('when "trust proxy" is disabled', function(){ - it('should ignore X-Forwarded-Host', function(done){ + describe('when "trust proxy" is disabled', function () { + it('should ignore X-Forwarded-Host', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.host); }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'evil') - .expect('localhost', done); - }) - }) - }) -}) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'evil') + .expect('localhost', done); + }); + }); + }); +}); diff --git a/test/req.hostname.js b/test/req.hostname.js index b3716b566ae..aac7b438bee 100644 --- a/test/req.hostname.js +++ b/test/req.hostname.js @@ -1,188 +1,180 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest') +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.hostname', function(){ - it('should return the Host when present', function(done){ +describe('req', function () { + describe('.hostname', function () { + it('should return the Host when present', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.hostname); }); request(app) - .post('/') - .set('Host', 'example.com') - .expect('example.com', done); - }) + .post('/') + .set('Host', 'example.com') + .expect('example.com', done); + }); - it('should strip port number', function(done){ + it('should strip port number', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.hostname); }); request(app) - .post('/') - .set('Host', 'example.com:3000') - .expect('example.com', done); - }) + .post('/') + .set('Host', 'example.com:3000') + .expect('example.com', done); + }); - it('should return undefined otherwise', function(done){ + it('should return undefined otherwise', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { req.headers.host = null; res.end(String(req.hostname)); }); - request(app) - .post('/') - .expect('undefined', done); - }) + request(app).post('/').expect('undefined', done); + }); - it('should work with IPv6 Host', function(done){ + it('should work with IPv6 Host', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.hostname); }); - request(app) - .post('/') - .set('Host', '[::1]') - .expect('[::1]', done); - }) + request(app).post('/').set('Host', '[::1]').expect('[::1]', done); + }); - it('should work with IPv6 Host and port', function(done){ + it('should work with IPv6 Host and port', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.hostname); }); - request(app) - .post('/') - .set('Host', '[::1]:3000') - .expect('[::1]', done); - }) + request(app).post('/').set('Host', '[::1]:3000').expect('[::1]', done); + }); - describe('when "trust proxy" is enabled', function(){ - it('should respect X-Forwarded-Host', function(done){ + describe('when "trust proxy" is enabled', function () { + it('should respect X-Forwarded-Host', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.hostname); }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com:3000') - .expect('example.com', done); - }) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com:3000') + .expect('example.com', done); + }); - it('should ignore X-Forwarded-Host if socket addr not trusted', function(done){ + it('should ignore X-Forwarded-Host if socket addr not trusted', function (done) { var app = express(); app.set('trust proxy', '10.0.0.1'); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.hostname); }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com') - .expect('localhost', done); - }) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com') + .expect('localhost', done); + }); - it('should default to Host', function(done){ + it('should default to Host', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.hostname); }); request(app) - .get('/') - .set('Host', 'example.com') - .expect('example.com', done); - }) + .get('/') + .set('Host', 'example.com') + .expect('example.com', done); + }); describe('when multiple X-Forwarded-Host', function () { it('should use the first value', function (done) { - var app = express() + var app = express(); - app.enable('trust proxy') + app.enable('trust proxy'); app.use(function (req, res) { - res.send(req.hostname) - }) + res.send(req.hostname); + }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com, foobar.com') - .expect(200, 'example.com', done) - }) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com, foobar.com') + .expect(200, 'example.com', done); + }); it('should remove OWS around comma', function (done) { - var app = express() + var app = express(); - app.enable('trust proxy') + app.enable('trust proxy'); app.use(function (req, res) { - res.send(req.hostname) - }) + res.send(req.hostname); + }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com , foobar.com') - .expect(200, 'example.com', done) - }) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com , foobar.com') + .expect(200, 'example.com', done); + }); it('should strip port number', function (done) { - var app = express() + var app = express(); - app.enable('trust proxy') + app.enable('trust proxy'); app.use(function (req, res) { - res.send(req.hostname) - }) + res.send(req.hostname); + }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com:8080 , foobar.com:8888') - .expect(200, 'example.com', done) - }) - }) - }) - - describe('when "trust proxy" is disabled', function(){ - it('should ignore X-Forwarded-Host', function(done){ + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com:8080 , foobar.com:8888') + .expect(200, 'example.com', done); + }); + }); + }); + + describe('when "trust proxy" is disabled', function () { + it('should ignore X-Forwarded-Host', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.hostname); }); request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'evil') - .expect('localhost', done); - }) - }) - }) -}) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'evil') + .expect('localhost', done); + }); + }); + }); +}); diff --git a/test/req.ip.js b/test/req.ip.js index 6bb3c5ac52f..2e01ef454d0 100644 --- a/test/req.ip.js +++ b/test/req.ip.js @@ -1,56 +1,56 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.ip', function(){ - describe('when X-Forwarded-For is present', function(){ - describe('when "trust proxy" is enabled', function(){ - it('should return the client addr', function(done){ +describe('req', function () { + describe('.ip', function () { + describe('when X-Forwarded-For is present', function () { + describe('when "trust proxy" is enabled', function () { + it('should return the client addr', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.send(req.ip); }); request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('client', done); - }) + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('client', done); + }); it('should return the addr after trusted proxy based on count', function (done) { var app = express(); app.set('trust proxy', 2); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.send(req.ip); }); request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('p1', done); - }) + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('p1', done); + }); it('should return the addr after trusted proxy based on list', function (done) { - var app = express() + var app = express(); - app.set('trust proxy', '10.0.0.1, 10.0.0.2, 127.0.0.1, ::1') + app.set('trust proxy', '10.0.0.1, 10.0.0.2, 127.0.0.1, ::1'); app.get('/', function (req, res) { - res.send(req.ip) - }) + res.send(req.ip); + }); request(app) .get('/') .set('X-Forwarded-For', '10.0.0.2, 10.0.0.3, 10.0.0.1', '10.0.0.4') - .expect('10.0.0.3', done) - }) + .expect('10.0.0.3', done); + }); it('should return the addr after trusted proxy, from sub app', function (done) { var app = express(); @@ -64,50 +64,48 @@ describe('req', function(){ }); request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect(200, 'p1', done); - }) - }) - - describe('when "trust proxy" is disabled', function(){ - it('should return the remote address', function(done){ + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect(200, 'p1', done); + }); + }); + + describe('when "trust proxy" is disabled', function () { + it('should return the remote address', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.send(req.ip); }); - var test = request(app).get('/') - test.set('X-Forwarded-For', 'client, p1, p2') + var test = request(app).get('/'); + test.set('X-Forwarded-For', 'client, p1, p2'); test.expect(200, getExpectedClientAddress(test._server), done); - }) - }) - }) + }); + }); + }); - describe('when X-Forwarded-For is not present', function(){ - it('should return the remote address', function(done){ + describe('when X-Forwarded-For is not present', function () { + it('should return the remote address', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.send(req.ip); }); - var test = request(app).get('/') - test.expect(200, getExpectedClientAddress(test._server), done) - }) - }) - }) -}) + var test = request(app).get('/'); + test.expect(200, getExpectedClientAddress(test._server), done); + }); + }); + }); +}); /** * Get the local client address depending on AF_NET of server */ function getExpectedClientAddress(server) { - return server.address().address === '::' - ? '::ffff:127.0.0.1' - : '127.0.0.1'; + return server.address().address === '::' ? '::ffff:127.0.0.1' : '127.0.0.1'; } diff --git a/test/req.ips.js b/test/req.ips.js index 2f9a0736ea3..bccedfeb219 100644 --- a/test/req.ips.js +++ b/test/req.ips.js @@ -1,71 +1,69 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.ips', function(){ - describe('when X-Forwarded-For is present', function(){ - describe('when "trust proxy" is enabled', function(){ - it('should return an array of the specified addresses', function(done){ +describe('req', function () { + describe('.ips', function () { + describe('when X-Forwarded-For is present', function () { + describe('when "trust proxy" is enabled', function () { + it('should return an array of the specified addresses', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.send(req.ips); }); request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('["client","p1","p2"]', done); - }) + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('["client","p1","p2"]', done); + }); - it('should stop at first untrusted', function(done){ + it('should stop at first untrusted', function (done) { var app = express(); app.set('trust proxy', 2); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.send(req.ips); }); request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('["p1","p2"]', done); - }) - }) + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('["p1","p2"]', done); + }); + }); - describe('when "trust proxy" is disabled', function(){ - it('should return an empty array', function(done){ + describe('when "trust proxy" is disabled', function () { + it('should return an empty array', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.send(req.ips); }); request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('[]', done); - }) - }) - }) + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('[]', done); + }); + }); + }); - describe('when X-Forwarded-For is not present', function(){ - it('should return []', function(done){ + describe('when X-Forwarded-For is not present', function () { + it('should return []', function (done) { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.send(req.ips); }); - request(app) - .get('/') - .expect('[]', done); - }) - }) - }) -}) + request(app).get('/').expect('[]', done); + }); + }); + }); +}); diff --git a/test/req.is.js b/test/req.is.js index c5904dd600a..4d31296edcc 100644 --- a/test/req.is.js +++ b/test/req.is.js @@ -1,169 +1,166 @@ -'use strict' +'use strict'; -var express = require('..') -var request = require('supertest') +var express = require('..'); +var request = require('supertest'); describe('req.is()', function () { describe('when given a mime type', function () { it('should return the type when matching', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('application/json')) - }) + res.json(req.is('application/json')); + }); request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, '"application/json"', done) - }) + .post('/') + .type('application/json') + .send('{}') + .expect(200, '"application/json"', done); + }); it('should return false when not matching', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('image/jpeg')) - }) + res.json(req.is('image/jpeg')); + }); request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, 'false', done) - }) + .post('/') + .type('application/json') + .send('{}') + .expect(200, 'false', done); + }); it('should ignore charset', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('application/json')) - }) + res.json(req.is('application/json')); + }); request(app) - .post('/') - .type('application/json; charset=UTF-8') - .send('{}') - .expect(200, '"application/json"', done) - }) - }) - - describe('when content-type is not present', function(){ + .post('/') + .type('application/json; charset=UTF-8') + .send('{}') + .expect(200, '"application/json"', done); + }); + }); + + describe('when content-type is not present', function () { it('should return false', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('application/json')) - }) + res.json(req.is('application/json')); + }); - request(app) - .post('/') - .send('{}') - .expect(200, 'false', done) - }) - }) + request(app).post('/').send('{}').expect(200, 'false', done); + }); + }); - describe('when given an extension', function(){ + describe('when given an extension', function () { it('should lookup the mime type', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('json')) - }) + res.json(req.is('json')); + }); request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, '"json"', done) - }) - }) - - describe('when given */subtype', function(){ + .post('/') + .type('application/json') + .send('{}') + .expect(200, '"json"', done); + }); + }); + + describe('when given */subtype', function () { it('should return the full type when matching', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('*/json')) - }) + res.json(req.is('*/json')); + }); request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, '"application/json"', done) - }) + .post('/') + .type('application/json') + .send('{}') + .expect(200, '"application/json"', done); + }); it('should return false when not matching', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('*/html')) - }) + res.json(req.is('*/html')); + }); request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, 'false', done) - }) + .post('/') + .type('application/json') + .send('{}') + .expect(200, 'false', done); + }); it('should ignore charset', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('*/json')) - }) + res.json(req.is('*/json')); + }); request(app) - .post('/') - .type('application/json; charset=UTF-8') - .send('{}') - .expect(200, '"application/json"', done) - }) - }) - - describe('when given type/*', function(){ + .post('/') + .type('application/json; charset=UTF-8') + .send('{}') + .expect(200, '"application/json"', done); + }); + }); + + describe('when given type/*', function () { it('should return the full type when matching', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('application/*')) - }) + res.json(req.is('application/*')); + }); request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, '"application/json"', done) - }) + .post('/') + .type('application/json') + .send('{}') + .expect(200, '"application/json"', done); + }); it('should return false when not matching', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('text/*')) - }) + res.json(req.is('text/*')); + }); request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, 'false', done) - }) + .post('/') + .type('application/json') + .send('{}') + .expect(200, 'false', done); + }); it('should ignore charset', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.is('application/*')) - }) + res.json(req.is('application/*')); + }); request(app) - .post('/') - .type('application/json; charset=UTF-8') - .send('{}') - .expect(200, '"application/json"', done) - }) - }) -}) + .post('/') + .type('application/json; charset=UTF-8') + .send('{}') + .expect(200, '"application/json"', done); + }); + }); +}); diff --git a/test/req.path.js b/test/req.path.js index 3ff6177c74e..7025df222e2 100644 --- a/test/req.path.js +++ b/test/req.path.js @@ -1,20 +1,20 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.path', function(){ - it('should return the parsed pathname', function(done){ +describe('req', function () { + describe('.path', function () { + it('should return the parsed pathname', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.path); }); request(app) - .get('/login?redirect=/post/1/comments') - .expect('/login', done); - }) - }) -}) + .get('/login?redirect=/post/1/comments') + .expect('/login', done); + }); + }); +}); diff --git a/test/req.protocol.js b/test/req.protocol.js index 61f76356b4c..359799fe211 100644 --- a/test/req.protocol.js +++ b/test/req.protocol.js @@ -1,81 +1,75 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.protocol', function(){ - it('should return the protocol string', function(done){ +describe('req', function () { + describe('.protocol', function () { + it('should return the protocol string', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.protocol); }); - request(app) - .get('/') - .expect('http', done); - }) + request(app).get('/').expect('http', done); + }); - describe('when "trust proxy" is enabled', function(){ - it('should respect X-Forwarded-Proto', function(done){ + describe('when "trust proxy" is enabled', function () { + it('should respect X-Forwarded-Proto', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.protocol); }); request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('https', done); - }) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('https', done); + }); - it('should default to the socket addr if X-Forwarded-Proto not present', function(done){ + it('should default to the socket addr if X-Forwarded-Proto not present', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res){ + app.use(function (req, res) { req.connection.encrypted = true; res.end(req.protocol); }); - request(app) - .get('/') - .expect('https', done); - }) + request(app).get('/').expect('https', done); + }); - it('should ignore X-Forwarded-Proto if socket addr not trusted', function(done){ + it('should ignore X-Forwarded-Proto if socket addr not trusted', function (done) { var app = express(); app.set('trust proxy', '10.0.0.1'); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.protocol); }); request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('http', done); - }) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('http', done); + }); - it('should default to http', function(done){ + it('should default to http', function (done) { var app = express(); app.enable('trust proxy'); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.protocol); }); - request(app) - .get('/') - .expect('http', done); - }) + request(app).get('/').expect('http', done); + }); describe('when trusting hop count', function () { it('should respect X-Forwarded-Proto', function (done) { @@ -88,26 +82,26 @@ describe('req', function(){ }); request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('https', done); - }) - }) - }) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('https', done); + }); + }); + }); - describe('when "trust proxy" is disabled', function(){ - it('should ignore X-Forwarded-Proto', function(done){ + describe('when "trust proxy" is disabled', function () { + it('should ignore X-Forwarded-Proto', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.end(req.protocol); }); request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('http', done); - }) - }) - }) -}) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('http', done); + }); + }); + }); +}); diff --git a/test/req.query.js b/test/req.query.js index bc76d4106b5..33583dbc8cc 100644 --- a/test/req.query.js +++ b/test/req.query.js @@ -1,25 +1,23 @@ -'use strict' +'use strict'; -var assert = require('assert') -var express = require('../') - , request = require('supertest'); +var assert = require('assert'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.query', function(){ - it('should default to {}', function(done){ +describe('req', function () { + describe('.query', function () { + it('should default to {}', function (done) { var app = createApp(); - request(app) - .get('/') - .expect(200, '{}', done); + request(app).get('/').expect(200, '{}', done); }); it('should default to parse simple keys', function (done) { var app = createApp(); request(app) - .get('/?user[name]=tj') - .expect(200, '{"user[name]":"tj"}', done); + .get('/?user[name]=tj') + .expect(200, '{"user[name]":"tj"}', done); }); describe('when "query parser" is extended', function () { @@ -27,16 +25,16 @@ describe('req', function(){ var app = createApp('extended'); request(app) - .get('/?foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!') - .expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done); + .get('/?foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!') + .expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done); }); it('should parse parameters with dots', function (done) { var app = createApp('extended'); request(app) - .get('/?user.name=tj') - .expect(200, '{"user.name":"tj"}', done); + .get('/?user.name=tj') + .expect(200, '{"user.name":"tj"}', done); }); }); @@ -45,20 +43,20 @@ describe('req', function(){ var app = createApp('simple'); request(app) - .get('/?user%5Bname%5D=tj') - .expect(200, '{"user[name]":"tj"}', done); + .get('/?user%5Bname%5D=tj') + .expect(200, '{"user[name]":"tj"}', done); }); }); describe('when "query parser" is a function', function () { it('should parse using function', function (done) { var app = createApp(function (str) { - return {'length': (str || '').length}; + return { length: (str || '').length }; }); request(app) - .get('/?user%5Bname%5D=tj') - .expect(200, '{"length":17}', done); + .get('/?user%5Bname%5D=tj') + .expect(200, '{"length":17}', done); }); }); @@ -66,9 +64,7 @@ describe('req', function(){ it('should not parse query', function (done) { var app = createApp(false); - request(app) - .get('/?user%5Bname%5D=tj') - .expect(200, '{}', done); + request(app).get('/?user%5Bname%5D=tj').expect(200, '{}', done); }); }); @@ -77,19 +73,21 @@ describe('req', function(){ var app = createApp(true); request(app) - .get('/?user%5Bname%5D=tj') - .expect(200, '{"user[name]":"tj"}', done); + .get('/?user%5Bname%5D=tj') + .expect(200, '{"user[name]":"tj"}', done); }); }); describe('when "query parser" an unknown value', function () { it('should throw', function () { - assert.throws(createApp.bind(null, 'bogus'), - /unknown value.*query parser/) + assert.throws( + createApp.bind(null, 'bogus'), + /unknown value.*query parser/, + ); }); }); - }) -}) + }); +}); function createApp(setting) { var app = express(); diff --git a/test/req.range.js b/test/req.range.js index 111441736eb..508ba78587f 100644 --- a/test/req.range.js +++ b/test/req.range.js @@ -1,104 +1,104 @@ -'use strict' +'use strict'; var express = require('..'); -var request = require('supertest') +var request = require('supertest'); -describe('req', function(){ - describe('.range(size)', function(){ +describe('req', function () { + describe('.range(size)', function () { it('should return parsed ranges', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.range(120)) - }) + res.json(req.range(120)); + }); request(app) - .get('/') - .set('Range', 'bytes=0-50,51-100') - .expect(200, '[{"start":0,"end":50},{"start":51,"end":100}]', done) - }) + .get('/') + .set('Range', 'bytes=0-50,51-100') + .expect(200, '[{"start":0,"end":50},{"start":51,"end":100}]', done); + }); it('should cap to the given size', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.range(75)) - }) + res.json(req.range(75)); + }); request(app) - .get('/') - .set('Range', 'bytes=0-100') - .expect(200, '[{"start":0,"end":74}]', done) - }) + .get('/') + .set('Range', 'bytes=0-100') + .expect(200, '[{"start":0,"end":74}]', done); + }); it('should cap to the given size when open-ended', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.range(75)) - }) + res.json(req.range(75)); + }); request(app) - .get('/') - .set('Range', 'bytes=0-') - .expect(200, '[{"start":0,"end":74}]', done) - }) + .get('/') + .set('Range', 'bytes=0-') + .expect(200, '[{"start":0,"end":74}]', done); + }); it('should have a .type', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.range(120).type) - }) + res.json(req.range(120).type); + }); request(app) - .get('/') - .set('Range', 'bytes=0-100') - .expect(200, '"bytes"', done) - }) + .get('/') + .set('Range', 'bytes=0-100') + .expect(200, '"bytes"', done); + }); it('should accept any type', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.range(120).type) - }) + res.json(req.range(120).type); + }); request(app) - .get('/') - .set('Range', 'users=0-2') - .expect(200, '"users"', done) - }) + .get('/') + .set('Range', 'users=0-2') + .expect(200, '"users"', done); + }); it('should return undefined if no range', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.send(String(req.range(120))) - }) + res.send(String(req.range(120))); + }); - request(app) - .get('/') - .expect(200, 'undefined', done) - }) - }) + request(app).get('/').expect(200, 'undefined', done); + }); + }); - describe('.range(size, options)', function(){ - describe('with "combine: true" option', function(){ + describe('.range(size, options)', function () { + describe('with "combine: true" option', function () { it('should return combined ranges', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.json(req.range(120, { - combine: true - })) - }) + res.json( + req.range(120, { + combine: true, + }), + ); + }); request(app) - .get('/') - .set('Range', 'bytes=0-50,51-100') - .expect(200, '[{"start":0,"end":100}]', done) - }) - }) - }) -}) + .get('/') + .set('Range', 'bytes=0-50,51-100') + .expect(200, '[{"start":0,"end":100}]', done); + }); + }); + }); +}); diff --git a/test/req.route.js b/test/req.route.js index 9bd7ed923b4..31e817f082e 100644 --- a/test/req.route.js +++ b/test/req.route.js @@ -1,20 +1,20 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.route', function(){ - it('should be the executed Route', function(done){ +describe('req', function () { + describe('.route', function () { + it('should be the executed Route', function (done) { var app = express(); - app.get('/user/:id{/:op}', function(req, res, next){ - res.header('path-1', req.route.path) + app.get('/user/:id{/:op}', function (req, res, next) { + res.header('path-1', req.route.path); next(); }); - app.get('/user/:id/edit', function(req, res){ - res.header('path-2', req.route.path) + app.get('/user/:id/edit', function (req, res) { + res.header('path-2', req.route.path); res.end(); }); @@ -22,7 +22,7 @@ describe('req', function(){ .get('/user/12/edit') .expect('path-1', '/user/:id{/:op}') .expect('path-2', '/user/:id/edit') - .expect(200, done) - }) - }) -}) + .expect(200, done); + }); + }); +}); diff --git a/test/req.secure.js b/test/req.secure.js index 0097ed6136e..da0069c9bc5 100644 --- a/test/req.secure.js +++ b/test/req.secure.js @@ -1,84 +1,82 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.secure', function(){ - describe('when X-Forwarded-Proto is missing', function(){ - it('should return false when http', function(done){ +describe('req', function () { + describe('.secure', function () { + describe('when X-Forwarded-Proto is missing', function () { + it('should return false when http', function (done) { var app = express(); - app.get('/', function(req, res){ + app.get('/', function (req, res) { res.send(req.secure ? 'yes' : 'no'); }); - request(app) - .get('/') - .expect('no', done) - }) - }) - }) - - describe('.secure', function(){ - describe('when X-Forwarded-Proto is present', function(){ - it('should return false when http', function(done){ + request(app).get('/').expect('no', done); + }); + }); + }); + + describe('.secure', function () { + describe('when X-Forwarded-Proto is present', function () { + it('should return false when http', function (done) { var app = express(); - app.get('/', function(req, res){ + app.get('/', function (req, res) { res.send(req.secure ? 'yes' : 'no'); }); request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('no', done) - }) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('no', done); + }); - it('should return true when "trust proxy" is enabled', function(done){ + it('should return true when "trust proxy" is enabled', function (done) { var app = express(); app.enable('trust proxy'); - app.get('/', function(req, res){ + app.get('/', function (req, res) { res.send(req.secure ? 'yes' : 'no'); }); request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('yes', done) - }) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('yes', done); + }); - it('should return false when initial proxy is http', function(done){ + it('should return false when initial proxy is http', function (done) { var app = express(); app.enable('trust proxy'); - app.get('/', function(req, res){ + app.get('/', function (req, res) { res.send(req.secure ? 'yes' : 'no'); }); request(app) - .get('/') - .set('X-Forwarded-Proto', 'http, https') - .expect('no', done) - }) + .get('/') + .set('X-Forwarded-Proto', 'http, https') + .expect('no', done); + }); - it('should return true when initial proxy is https', function(done){ + it('should return true when initial proxy is https', function (done) { var app = express(); app.enable('trust proxy'); - app.get('/', function(req, res){ + app.get('/', function (req, res) { res.send(req.secure ? 'yes' : 'no'); }); request(app) - .get('/') - .set('X-Forwarded-Proto', 'https, http') - .expect('yes', done) - }) + .get('/') + .set('X-Forwarded-Proto', 'https, http') + .expect('yes', done); + }); describe('when "trust proxy" trusting hop count', function () { it('should respect X-Forwarded-Proto', function (done) { @@ -91,11 +89,11 @@ describe('req', function(){ }); request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('yes', done) - }) - }) - }) - }) -}) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('yes', done); + }); + }); + }); + }); +}); diff --git a/test/req.signedCookies.js b/test/req.signedCookies.js index db561951665..2d9538f0968 100644 --- a/test/req.signedCookies.js +++ b/test/req.signedCookies.js @@ -1,17 +1,17 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest') - , cookieParser = require('cookie-parser') +var express = require('../'), + request = require('supertest'), + cookieParser = require('cookie-parser'); -describe('req', function(){ - describe('.signedCookies', function(){ - it('should return a signed JSON cookie', function(done){ +describe('req', function () { + describe('.signedCookies', function () { + it('should return a signed JSON cookie', function (done) { var app = express(); app.use(cookieParser('secret')); - app.use(function(req, res){ + app.use(function (req, res) { if (req.path === '/set') { res.cookie('obj', { foo: 'bar' }, { signed: true }); res.end(); @@ -21,17 +21,16 @@ describe('req', function(){ }); request(app) - .get('/set') - .end(function(err, res){ - if (err) return done(err); - var cookie = res.header['set-cookie']; - - request(app) - .get('/') - .set('Cookie', cookie) - .expect(200, { obj: { foo: 'bar' } }, done) - }); - }) - }) -}) + .get('/set') + .end(function (err, res) { + if (err) return done(err); + var cookie = res.header['set-cookie']; + request(app) + .get('/') + .set('Cookie', cookie) + .expect(200, { obj: { foo: 'bar' } }, done); + }); + }); + }); +}); diff --git a/test/req.stale.js b/test/req.stale.js index cda77fa403e..529ea2e5d3f 100644 --- a/test/req.stale.js +++ b/test/req.stale.js @@ -1,50 +1,45 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.stale', function(){ - it('should return false when the resource is not modified', function(done){ +describe('req', function () { + describe('.stale', function () { + it('should return false when the resource is not modified', function (done) { var app = express(); var etag = '"12345"'; - app.use(function(req, res){ + app.use(function (req, res) { res.set('ETag', etag); res.send(req.stale); }); - request(app) - .get('/') - .set('If-None-Match', etag) - .expect(304, done); - }) + request(app).get('/').set('If-None-Match', etag).expect(304, done); + }); - it('should return true when the resource is modified', function(done){ + it('should return true when the resource is modified', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.set('ETag', '"123"'); res.send(req.stale); }); request(app) - .get('/') - .set('If-None-Match', '"12345"') - .expect(200, 'true', done); - }) + .get('/') + .set('If-None-Match', '"12345"') + .expect(200, 'true', done); + }); - it('should return true without response headers', function(done){ + it('should return true without response headers', function (done) { var app = express(); - app.disable('x-powered-by') - app.use(function(req, res){ + app.disable('x-powered-by'); + app.use(function (req, res) { res.send(req.stale); }); - request(app) - .get('/') - .expect(200, 'true', done); - }) - }) -}) + request(app).get('/').expect(200, 'true', done); + }); + }); +}); diff --git a/test/req.subdomains.js b/test/req.subdomains.js index e5600f2eb56..9f472ed122b 100644 --- a/test/req.subdomains.js +++ b/test/req.subdomains.js @@ -1,80 +1,69 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.subdomains', function(){ - describe('when present', function(){ - it('should return an array', function(done){ +describe('req', function () { + describe('.subdomains', function () { + describe('when present', function () { + it('should return an array', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send(req.subdomains); }); request(app) - .get('/') - .set('Host', 'tobi.ferrets.example.com') - .expect(200, ['ferrets', 'tobi'], done); - }) + .get('/') + .set('Host', 'tobi.ferrets.example.com') + .expect(200, ['ferrets', 'tobi'], done); + }); - it('should work with IPv4 address', function(done){ + it('should work with IPv4 address', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send(req.subdomains); }); - request(app) - .get('/') - .set('Host', '127.0.0.1') - .expect(200, [], done); - }) + request(app).get('/').set('Host', '127.0.0.1').expect(200, [], done); + }); - it('should work with IPv6 address', function(done){ + it('should work with IPv6 address', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send(req.subdomains); }); - request(app) - .get('/') - .set('Host', '[::1]') - .expect(200, [], done); - }) - }) - - describe('otherwise', function(){ - it('should return an empty array', function(done){ + request(app).get('/').set('Host', '[::1]').expect(200, [], done); + }); + }); + + describe('otherwise', function () { + it('should return an empty array', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send(req.subdomains); }); - request(app) - .get('/') - .set('Host', 'example.com') - .expect(200, [], done); - }) - }) - - describe('with no host', function(){ - it('should return an empty array', function(done){ + request(app).get('/').set('Host', 'example.com').expect(200, [], done); + }); + }); + + describe('with no host', function () { + it('should return an empty array', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { req.headers.host = null; res.send(req.subdomains); }); - request(app) - .get('/') - .expect(200, [], done); - }) - }) + request(app).get('/').expect(200, [], done); + }); + }); describe('with trusted X-Forwarded-Host', function () { it('should return an array', function (done) { @@ -86,88 +75,88 @@ describe('req', function(){ }); request(app) - .get('/') - .set('X-Forwarded-Host', 'tobi.ferrets.example.com') - .expect(200, ['ferrets', 'tobi'], done); - }) - }) - - describe('when subdomain offset is set', function(){ - describe('when subdomain offset is zero', function(){ - it('should return an array with the whole domain', function(done){ + .get('/') + .set('X-Forwarded-Host', 'tobi.ferrets.example.com') + .expect(200, ['ferrets', 'tobi'], done); + }); + }); + + describe('when subdomain offset is set', function () { + describe('when subdomain offset is zero', function () { + it('should return an array with the whole domain', function (done) { var app = express(); app.set('subdomain offset', 0); - app.use(function(req, res){ + app.use(function (req, res) { res.send(req.subdomains); }); request(app) - .get('/') - .set('Host', 'tobi.ferrets.sub.example.com') - .expect(200, ['com', 'example', 'sub', 'ferrets', 'tobi'], done); - }) + .get('/') + .set('Host', 'tobi.ferrets.sub.example.com') + .expect(200, ['com', 'example', 'sub', 'ferrets', 'tobi'], done); + }); it('should return an array with the whole IPv4', function (done) { var app = express(); app.set('subdomain offset', 0); - app.use(function(req, res){ + app.use(function (req, res) { res.send(req.subdomains); }); request(app) - .get('/') - .set('Host', '127.0.0.1') - .expect(200, ['127.0.0.1'], done); - }) + .get('/') + .set('Host', '127.0.0.1') + .expect(200, ['127.0.0.1'], done); + }); it('should return an array with the whole IPv6', function (done) { var app = express(); app.set('subdomain offset', 0); - app.use(function(req, res){ + app.use(function (req, res) { res.send(req.subdomains); }); request(app) - .get('/') - .set('Host', '[::1]') - .expect(200, ['[::1]'], done); - }) - }) + .get('/') + .set('Host', '[::1]') + .expect(200, ['[::1]'], done); + }); + }); - describe('when present', function(){ - it('should return an array', function(done){ + describe('when present', function () { + it('should return an array', function (done) { var app = express(); app.set('subdomain offset', 3); - app.use(function(req, res){ + app.use(function (req, res) { res.send(req.subdomains); }); request(app) - .get('/') - .set('Host', 'tobi.ferrets.sub.example.com') - .expect(200, ['ferrets', 'tobi'], done); - }) - }) + .get('/') + .set('Host', 'tobi.ferrets.sub.example.com') + .expect(200, ['ferrets', 'tobi'], done); + }); + }); - describe('otherwise', function(){ - it('should return an empty array', function(done){ + describe('otherwise', function () { + it('should return an empty array', function (done) { var app = express(); app.set('subdomain offset', 3); - app.use(function(req, res){ + app.use(function (req, res) { res.send(req.subdomains); }); request(app) - .get('/') - .set('Host', 'sub.example.com') - .expect(200, [], done); - }) - }) - }) - }) -}) + .get('/') + .set('Host', 'sub.example.com') + .expect(200, [], done); + }); + }); + }); + }); +}); diff --git a/test/req.xhr.js b/test/req.xhr.js index 99cf7f1917d..5590f9e496c 100644 --- a/test/req.xhr.js +++ b/test/req.xhr.js @@ -1,42 +1,40 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('req', function(){ - describe('.xhr', function(){ +describe('req', function () { + describe('.xhr', function () { before(function () { - this.app = express() + this.app = express(); this.app.get('/', function (req, res) { - res.send(req.xhr) - }) - }) + res.send(req.xhr); + }); + }); - it('should return true when X-Requested-With is xmlhttprequest', function(done){ + it('should return true when X-Requested-With is xmlhttprequest', function (done) { request(this.app) .get('/') .set('X-Requested-With', 'xmlhttprequest') - .expect(200, 'true', done) - }) + .expect(200, 'true', done); + }); - it('should case-insensitive', function(done){ + it('should case-insensitive', function (done) { request(this.app) .get('/') .set('X-Requested-With', 'XMLHttpRequest') - .expect(200, 'true', done) - }) + .expect(200, 'true', done); + }); - it('should return false otherwise', function(done){ + it('should return false otherwise', function (done) { request(this.app) .get('/') .set('X-Requested-With', 'blahblah') - .expect(200, 'false', done) - }) + .expect(200, 'false', done); + }); - it('should return false when not present', function(done){ - request(this.app) - .get('/') - .expect(200, 'false', done) - }) - }) -}) + it('should return false when not present', function (done) { + request(this.app).get('/').expect(200, 'false', done); + }); + }); +}); diff --git a/test/res.append.js b/test/res.append.js index 8f72598bf52..be24bbf5902 100644 --- a/test/res.append.js +++ b/test/res.append.js @@ -1,116 +1,125 @@ -'use strict' +'use strict'; -var assert = require('assert') -var express = require('..') -var request = require('supertest') +var assert = require('assert'); +var express = require('..'); +var request = require('supertest'); describe('res', function () { describe('.append(field, val)', function () { it('should append multiple headers', function (done) { - var app = express() + var app = express(); app.use(function (req, res, next) { - res.append('Set-Cookie', 'foo=bar') - next() - }) + res.append('Set-Cookie', 'foo=bar'); + next(); + }); app.use(function (req, res) { - res.append('Set-Cookie', 'fizz=buzz') - res.end() - }) + res.append('Set-Cookie', 'fizz=buzz'); + res.end(); + }); request(app) .get('/') .expect(200) .expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar', 'fizz=buzz'])) - .end(done) - }) + .end(done); + }); it('should accept array of values', function (done) { - var app = express() + var app = express(); app.use(function (req, res, next) { - res.append('Set-Cookie', ['foo=bar', 'fizz=buzz']) - res.end() - }) + res.append('Set-Cookie', ['foo=bar', 'fizz=buzz']); + res.end(); + }); request(app) .get('/') .expect(200) .expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar', 'fizz=buzz'])) - .end(done) - }) + .end(done); + }); it('should get reset by res.set(field, val)', function (done) { - var app = express() + var app = express(); app.use(function (req, res, next) { - res.append('Set-Cookie', 'foo=bar') - res.append('Set-Cookie', 'fizz=buzz') - next() - }) + res.append('Set-Cookie', 'foo=bar'); + res.append('Set-Cookie', 'fizz=buzz'); + next(); + }); app.use(function (req, res) { - res.set('Set-Cookie', 'pet=tobi') - res.end() + res.set('Set-Cookie', 'pet=tobi'); + res.end(); }); request(app) .get('/') .expect(200) .expect(shouldHaveHeaderValues('Set-Cookie', ['pet=tobi'])) - .end(done) - }) + .end(done); + }); it('should work with res.set(field, val) first', function (done) { - var app = express() + var app = express(); app.use(function (req, res, next) { - res.set('Set-Cookie', 'foo=bar') - next() - }) + res.set('Set-Cookie', 'foo=bar'); + next(); + }); - app.use(function(req, res){ - res.append('Set-Cookie', 'fizz=buzz') - res.end() - }) + app.use(function (req, res) { + res.append('Set-Cookie', 'fizz=buzz'); + res.end(); + }); request(app) .get('/') .expect(200) .expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar', 'fizz=buzz'])) - .end(done) - }) + .end(done); + }); it('should work together with res.cookie', function (done) { - var app = express() + var app = express(); app.use(function (req, res, next) { - res.cookie('foo', 'bar') - next() - }) + res.cookie('foo', 'bar'); + next(); + }); app.use(function (req, res) { - res.append('Set-Cookie', 'fizz=buzz') - res.end() - }) + res.append('Set-Cookie', 'fizz=buzz'); + res.end(); + }); request(app) .get('/') .expect(200) - .expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar; Path=/', 'fizz=buzz'])) - .end(done) - }) - }) -}) - -function shouldHaveHeaderValues (key, values) { + .expect( + shouldHaveHeaderValues('Set-Cookie', [ + 'foo=bar; Path=/', + 'fizz=buzz', + ]), + ) + .end(done); + }); + }); +}); + +function shouldHaveHeaderValues(key, values) { return function (res) { - var headers = res.headers[key.toLowerCase()] - assert.ok(headers, 'should have header "' + key + '"') - assert.strictEqual(headers.length, values.length, 'should have ' + values.length + ' occurances of "' + key + '"') + var headers = res.headers[key.toLowerCase()]; + assert.ok(headers, 'should have header "' + key + '"'); + assert.strictEqual( + headers.length, + values.length, + 'should have ' + values.length + ' occurances of "' + key + '"', + ); for (var i = 0; i < values.length; i++) { - assert.strictEqual(headers[i], values[i]) + assert.strictEqual(headers[i], values[i]); } - } + }; } diff --git a/test/res.attachment.js b/test/res.attachment.js index 6283ded0d65..4c3d1636012 100644 --- a/test/res.attachment.js +++ b/test/res.attachment.js @@ -1,78 +1,81 @@ -'use strict' +'use strict'; -var Buffer = require('safe-buffer').Buffer -var express = require('../') - , request = require('supertest'); +var Buffer = require('safe-buffer').Buffer; +var express = require('../'), + request = require('supertest'); -describe('res', function(){ - describe('.attachment()', function(){ - it('should Content-Disposition to attachment', function(done){ +describe('res', function () { + describe('.attachment()', function () { + it('should Content-Disposition to attachment', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.attachment().send('foo'); }); - request(app) - .get('/') - .expect('Content-Disposition', 'attachment', done); - }) - }) + request(app).get('/').expect('Content-Disposition', 'attachment', done); + }); + }); - describe('.attachment(filename)', function(){ - it('should add the filename param', function(done){ + describe('.attachment(filename)', function () { + it('should add the filename param', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.attachment('/path/to/image.png'); res.send('foo'); }); request(app) - .get('/') - .expect('Content-Disposition', 'attachment; filename="image.png"', done); - }) - - it('should set the Content-Type', function(done){ + .get('/') + .expect( + 'Content-Disposition', + 'attachment; filename="image.png"', + done, + ); + }); + + it('should set the Content-Type', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.attachment('/path/to/image.png'); - res.send(Buffer.alloc(4, '.')) + res.send(Buffer.alloc(4, '.')); }); - request(app) - .get('/') - .expect('Content-Type', 'image/png', done); - }) - }) + request(app).get('/').expect('Content-Type', 'image/png', done); + }); + }); - describe('.attachment(utf8filename)', function(){ - it('should add the filename and filename* params', function(done){ + describe('.attachment(utf8filename)', function () { + it('should add the filename and filename* params', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.attachment('/locales/日本語.txt'); res.send('japanese'); }); request(app) - .get('/') - .expect('Content-Disposition', 'attachment; filename="???.txt"; filename*=UTF-8\'\'%E6%97%A5%E6%9C%AC%E8%AA%9E.txt') - .expect(200, done); - }) - - it('should set the Content-Type', function(done){ + .get('/') + .expect( + 'Content-Disposition', + 'attachment; filename="???.txt"; filename*=UTF-8\'\'%E6%97%A5%E6%9C%AC%E8%AA%9E.txt', + ) + .expect(200, done); + }); + + it('should set the Content-Type', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.attachment('/locales/日本語.txt'); res.send('japanese'); }); request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=utf-8', done); - }) - }) -}) + .get('/') + .expect('Content-Type', 'text/plain; charset=utf-8', done); + }); + }); +}); diff --git a/test/res.clearCookie.js b/test/res.clearCookie.js index 74a746eb7be..92629bda520 100644 --- a/test/res.clearCookie.js +++ b/test/res.clearCookie.js @@ -1,62 +1,74 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('res', function(){ - describe('.clearCookie(name)', function(){ - it('should set a cookie passed expiry', function(done){ +describe('res', function () { + describe('.clearCookie(name)', function () { + it('should set a cookie passed expiry', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.clearCookie('sid').end(); }); request(app) - .get('/') - .expect('Set-Cookie', 'sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT') - .expect(200, done) - }) - }) - - describe('.clearCookie(name, options)', function(){ - it('should set the given params', function(done){ + .get('/') + .expect( + 'Set-Cookie', + 'sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT', + ) + .expect(200, done); + }); + }); + + describe('.clearCookie(name, options)', function () { + it('should set the given params', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.clearCookie('sid', { path: '/admin' }).end(); }); request(app) - .get('/') - .expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') - .expect(200, done) - }) + .get('/') + .expect( + 'Set-Cookie', + 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT', + ) + .expect(200, done); + }); - it('should ignore maxAge', function(done){ + it('should ignore maxAge', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.clearCookie('sid', { path: '/admin', maxAge: 1000 }).end(); }); request(app) - .get('/') - .expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') - .expect(200, done) - }) + .get('/') + .expect( + 'Set-Cookie', + 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT', + ) + .expect(200, done); + }); - it('should ignore user supplied expires param', function(done){ + it('should ignore user supplied expires param', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.clearCookie('sid', { path: '/admin', expires: new Date() }).end(); }); request(app) - .get('/') - .expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') - .expect(200, done) - }) - }) -}) + .get('/') + .expect( + 'Set-Cookie', + 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT', + ) + .expect(200, done); + }); + }); +}); diff --git a/test/res.cookie.js b/test/res.cookie.js index c837820605c..1239e5ed1dc 100644 --- a/test/res.cookie.js +++ b/test/res.cookie.js @@ -1,44 +1,44 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest') - , cookieParser = require('cookie-parser') +var express = require('../'), + request = require('supertest'), + cookieParser = require('cookie-parser'); var merge = require('utils-merge'); -describe('res', function(){ - describe('.cookie(name, object)', function(){ - it('should generate a JSON cookie', function(done){ +describe('res', function () { + describe('.cookie(name, object)', function () { + it('should generate a JSON cookie', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.cookie('user', { name: 'tobi' }).end(); }); request(app) - .get('/') - .expect('Set-Cookie', 'user=j%3A%7B%22name%22%3A%22tobi%22%7D; Path=/') - .expect(200, done) - }) - }) - - describe('.cookie(name, string)', function(){ - it('should set a cookie', function(done){ + .get('/') + .expect('Set-Cookie', 'user=j%3A%7B%22name%22%3A%22tobi%22%7D; Path=/') + .expect(200, done); + }); + }); + + describe('.cookie(name, string)', function () { + it('should set a cookie', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.cookie('name', 'tobi').end(); }); request(app) - .get('/') - .expect('Set-Cookie', 'name=tobi; Path=/') - .expect(200, done) - }) + .get('/') + .expect('Set-Cookie', 'name=tobi; Path=/') + .expect(200, done); + }); - it('should allow multiple calls', function(done){ + it('should allow multiple calls', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.cookie('name', 'tobi'); res.cookie('age', 1); res.cookie('gender', '?'); @@ -47,40 +47,43 @@ describe('res', function(){ request(app) .get('/') - .expect('Set-Cookie', 'name=tobi; Path=/,age=1; Path=/,gender=%3F; Path=/') - .expect(200, done) - }) - }) - - describe('.cookie(name, string, options)', function(){ - it('should set params', function(done){ + .expect( + 'Set-Cookie', + 'name=tobi; Path=/,age=1; Path=/,gender=%3F; Path=/', + ) + .expect(200, done); + }); + }); + + describe('.cookie(name, string, options)', function () { + it('should set params', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.cookie('name', 'tobi', { httpOnly: true, secure: true }); res.end(); }); request(app) - .get('/') - .expect('Set-Cookie', 'name=tobi; Path=/; HttpOnly; Secure') - .expect(200, done) - }) + .get('/') + .expect('Set-Cookie', 'name=tobi; Path=/; HttpOnly; Secure') + .expect(200, done); + }); describe('expires', function () { it('should throw on invalid date', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.cookie('name', 'tobi', { expires: new Date(NaN) }) - res.end() - }) + res.cookie('name', 'tobi', { expires: new Date(NaN) }); + res.end(); + }); request(app) .get('/') - .expect(500, /option expires is invalid/, done) - }) - }) + .expect(500, /option expires is invalid/, done); + }); + }); describe('partitioned', function () { it('should set partitioned', function (done) { @@ -94,15 +97,15 @@ describe('res', function(){ request(app) .get('/') .expect('Set-Cookie', 'name=tobi; Path=/; Partitioned') - .expect(200, done) - }) - }) + .expect(200, done); + }); + }); - describe('maxAge', function(){ - it('should set relative expires', function(done){ + describe('maxAge', function () { + it('should set relative expires', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.cookie('name', 'tobi', { maxAge: 1000 }); res.end(); }); @@ -110,187 +113,191 @@ describe('res', function(){ request(app) .get('/') .expect('Set-Cookie', /name=tobi; Max-Age=1; Path=\/; Expires=/) - .expect(200, done) - }) + .expect(200, done); + }); - it('should set max-age', function(done){ + it('should set max-age', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.cookie('name', 'tobi', { maxAge: 1000 }); res.end(); }); request(app) - .get('/') - .expect('Set-Cookie', /Max-Age=1/, done) - }) + .get('/') + .expect('Set-Cookie', /Max-Age=1/, done); + }); - it('should not mutate the options object', function(done){ + it('should not mutate the options object', function (done) { var app = express(); var options = { maxAge: 1000 }; var optionsCopy = merge({}, options); - app.use(function(req, res){ - res.cookie('name', 'tobi', options) - res.json(options) + app.use(function (req, res) { + res.cookie('name', 'tobi', options); + res.json(options); }); - request(app) - .get('/') - .expect(200, optionsCopy, done) - }) + request(app).get('/').expect(200, optionsCopy, done); + }); it('should not throw on null', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.cookie('name', 'tobi', { maxAge: null }) - res.end() - }) + res.cookie('name', 'tobi', { maxAge: null }); + res.end(); + }); request(app) .get('/') .expect(200) .expect('Set-Cookie', 'name=tobi; Path=/') - .end(done) - }) + .end(done); + }); it('should not throw on undefined', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.cookie('name', 'tobi', { maxAge: undefined }) - res.end() - }) + res.cookie('name', 'tobi', { maxAge: undefined }); + res.end(); + }); request(app) .get('/') .expect(200) .expect('Set-Cookie', 'name=tobi; Path=/') - .end(done) - }) + .end(done); + }); it('should throw an error with invalid maxAge', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.cookie('name', 'tobi', { maxAge: 'foobar' }) - res.end() - }) + res.cookie('name', 'tobi', { maxAge: 'foobar' }); + res.end(); + }); request(app) .get('/') - .expect(500, /option maxAge is invalid/, done) - }) - }) + .expect(500, /option maxAge is invalid/, done); + }); + }); describe('priority', function () { it('should set low priority', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.cookie('name', 'tobi', { priority: 'low' }) - res.end() - }) + res.cookie('name', 'tobi', { priority: 'low' }); + res.end(); + }); request(app) .get('/') .expect('Set-Cookie', /Priority=Low/) - .expect(200, done) - }) + .expect(200, done); + }); it('should set medium priority', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.cookie('name', 'tobi', { priority: 'medium' }) - res.end() - }) + res.cookie('name', 'tobi', { priority: 'medium' }); + res.end(); + }); request(app) .get('/') .expect('Set-Cookie', /Priority=Medium/) - .expect(200, done) - }) + .expect(200, done); + }); it('should set high priority', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.cookie('name', 'tobi', { priority: 'high' }) - res.end() - }) + res.cookie('name', 'tobi', { priority: 'high' }); + res.end(); + }); request(app) .get('/') .expect('Set-Cookie', /Priority=High/) - .expect(200, done) - }) + .expect(200, done); + }); it('should throw with invalid priority', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.cookie('name', 'tobi', { priority: 'foobar' }) - res.end() - }) + res.cookie('name', 'tobi', { priority: 'foobar' }); + res.end(); + }); request(app) .get('/') - .expect(500, /option priority is invalid/, done) - }) - }) + .expect(500, /option priority is invalid/, done); + }); + }); - describe('signed', function(){ - it('should generate a signed JSON cookie', function(done){ + describe('signed', function () { + it('should generate a signed JSON cookie', function (done) { var app = express(); app.use(cookieParser('foo bar baz')); - app.use(function(req, res){ + app.use(function (req, res) { res.cookie('user', { name: 'tobi' }, { signed: true }).end(); }); request(app) .get('/') - .expect('Set-Cookie', 'user=s%3Aj%3A%7B%22name%22%3A%22tobi%22%7D.K20xcwmDS%2BPb1rsD95o5Jm5SqWs1KteqdnynnB7jkTE; Path=/') - .expect(200, done) - }) - }) + .expect( + 'Set-Cookie', + 'user=s%3Aj%3A%7B%22name%22%3A%22tobi%22%7D.K20xcwmDS%2BPb1rsD95o5Jm5SqWs1KteqdnynnB7jkTE; Path=/', + ) + .expect(200, done); + }); + }); - describe('signed without secret', function(){ - it('should throw an error', function(done){ + describe('signed without secret', function () { + it('should throw an error', function (done) { var app = express(); app.use(cookieParser()); - app.use(function(req, res){ + app.use(function (req, res) { res.cookie('name', 'tobi', { signed: true }).end(); }); request(app) - .get('/') - .expect(500, /secret\S+ required for signed cookies/, done); - }) - }) + .get('/') + .expect(500, /secret\S+ required for signed cookies/, done); + }); + }); - describe('.signedCookie(name, string)', function(){ - it('should set a signed cookie', function(done){ + describe('.signedCookie(name, string)', function () { + it('should set a signed cookie', function (done) { var app = express(); app.use(cookieParser('foo bar baz')); - app.use(function(req, res){ + app.use(function (req, res) { res.cookie('name', 'tobi', { signed: true }).end(); }); request(app) - .get('/') - .expect('Set-Cookie', 'name=s%3Atobi.xJjV2iZ6EI7C8E5kzwbfA9PVLl1ZR07UTnuTgQQ4EnQ; Path=/') - .expect(200, done) - }) - }) - }) -}) + .get('/') + .expect( + 'Set-Cookie', + 'name=s%3Atobi.xJjV2iZ6EI7C8E5kzwbfA9PVLl1ZR07UTnuTgQQ4EnQ; Path=/', + ) + .expect(200, done); + }); + }); + }); +}); diff --git a/test/res.download.js b/test/res.download.js index f7d795d57c0..9c5c52f5ba8 100644 --- a/test/res.download.js +++ b/test/res.download.js @@ -1,166 +1,165 @@ -'use strict' +'use strict'; var after = require('after'); -var assert = require('assert') -var asyncHooks = tryRequire('async_hooks') -var Buffer = require('safe-buffer').Buffer +var assert = require('assert'); +var asyncHooks = tryRequire('async_hooks'); +var Buffer = require('safe-buffer').Buffer; var express = require('..'); -var path = require('path') +var path = require('path'); var request = require('supertest'); -var utils = require('./support/utils') +var utils = require('./support/utils'); -var FIXTURES_PATH = path.join(__dirname, 'fixtures') +var FIXTURES_PATH = path.join(__dirname, 'fixtures'); -var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function' - ? describe - : describe.skip +var describeAsyncHooks = + typeof asyncHooks.AsyncLocalStorage === 'function' ? describe : describe.skip; -describe('res', function(){ - describe('.download(path)', function(){ - it('should transfer as an attachment', function(done){ +describe('res', function () { + describe('.download(path)', function () { + it('should transfer as an attachment', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.download('test/fixtures/user.html'); }); request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="user.html"') - .expect(200, '

        {{user.name}}

        ', done) - }) + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="user.html"') + .expect(200, '

        {{user.name}}

        ', done); + }); it('should accept range requests', function (done) { - var app = express() + var app = express(); app.get('/', function (req, res) { - res.download('test/fixtures/user.html') - }) + res.download('test/fixtures/user.html'); + }); request(app) .get('/') .expect('Accept-Ranges', 'bytes') - .expect(200, '

        {{user.name}}

        ', done) - }) + .expect(200, '

        {{user.name}}

        ', done); + }); it('should respond with requested byte range', function (done) { - var app = express() + var app = express(); app.get('/', function (req, res) { - res.download('test/fixtures/user.html') - }) + res.download('test/fixtures/user.html'); + }); request(app) .get('/') .set('Range', 'bytes=0-2') .expect('Content-Range', 'bytes 0-2/20') - .expect(206, '

        ', done) - }) - }) + .expect(206, '

        ', done); + }); + }); - describe('.download(path, filename)', function(){ - it('should provide an alternate filename', function(done){ + describe('.download(path, filename)', function () { + it('should provide an alternate filename', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.download('test/fixtures/user.html', 'document'); }); request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="document"') - .expect(200, done) - }) - }) - - describe('.download(path, fn)', function(){ - it('should invoke the callback', function(done){ + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="document"') + .expect(200, done); + }); + }); + + describe('.download(path, fn)', function () { + it('should invoke the callback', function (done) { var app = express(); var cb = after(2, done); - app.use(function(req, res){ + app.use(function (req, res) { res.download('test/fixtures/user.html', cb); }); request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="user.html"') - .expect(200, cb); - }) + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="user.html"') + .expect(200, cb); + }); describeAsyncHooks('async local storage', function () { it('should presist store', function (done) { - var app = express() - var cb = after(2, done) - var store = { foo: 'bar' } + var app = express(); + var cb = after(2, done); + var store = { foo: 'bar' }; app.use(function (req, res, next) { - req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage() - req.asyncLocalStorage.run(store, next) - }) + req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage(); + req.asyncLocalStorage.run(store, next); + }); app.use(function (req, res) { res.download('test/fixtures/name.txt', function (err) { - if (err) return cb(err) + if (err) return cb(err); - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); - assert.strictEqual(local.foo, 'bar') - cb() - }) - }) + assert.strictEqual(local.foo, 'bar'); + cb(); + }); + }); request(app) .get('/') .expect('Content-Type', 'text/plain; charset=utf-8') .expect('Content-Disposition', 'attachment; filename="name.txt"') - .expect(200, 'tobi', cb) - }) + .expect(200, 'tobi', cb); + }); it('should presist store on error', function (done) { - var app = express() - var store = { foo: 'bar' } + var app = express(); + var store = { foo: 'bar' }; app.use(function (req, res, next) { - req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage() - req.asyncLocalStorage.run(store, next) - }) + req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage(); + req.asyncLocalStorage.run(store, next); + }); app.use(function (req, res) { res.download('test/fixtures/does-not-exist', function (err) { - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); if (local) { - res.setHeader('x-store-foo', String(local.foo)) + res.setHeader('x-store-foo', String(local.foo)); } - res.send(err ? 'got ' + err.status + ' error' : 'no error') - }) - }) + res.send(err ? 'got ' + err.status + ' error' : 'no error'); + }); + }); request(app) .get('/') .expect(200) .expect('x-store-foo', 'bar') .expect('got 404 error') - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); describe('.download(path, options)', function () { it('should allow options to res.sendFile()', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/.name', { dotfiles: 'allow', - maxAge: '4h' - }) - }) + maxAge: '4h', + }); + }); request(app) .get('/') @@ -168,240 +167,241 @@ describe('res', function(){ .expect('Content-Disposition', 'attachment; filename=".name"') .expect('Cache-Control', 'public, max-age=14400') .expect(utils.shouldHaveBody(Buffer.from('tobi'))) - .end(done) - }) + .end(done); + }); describe('with "headers" option', function () { it('should set headers on response', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/user.html', { headers: { 'X-Foo': 'Bar', - 'X-Bar': 'Foo' - } - }) - }) + 'X-Bar': 'Foo', + }, + }); + }); request(app) .get('/') .expect(200) .expect('X-Foo', 'Bar') .expect('X-Bar', 'Foo') - .end(done) - }) + .end(done); + }); it('should use last header when duplicated', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/user.html', { headers: { 'X-Foo': 'Bar', - 'x-foo': 'bar' - } - }) - }) + 'x-foo': 'bar', + }, + }); + }); - request(app) - .get('/') - .expect(200) - .expect('X-Foo', 'bar') - .end(done) - }) + request(app).get('/').expect(200).expect('X-Foo', 'bar').end(done); + }); it('should override Content-Type', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/user.html', { headers: { - 'Content-Type': 'text/x-custom' - } - }) - }) + 'Content-Type': 'text/x-custom', + }, + }); + }); request(app) .get('/') .expect(200) .expect('Content-Type', 'text/x-custom') - .end(done) - }) + .end(done); + }); it('should not set headers on 404', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/does-not-exist', { headers: { - 'X-Foo': 'Bar' - } - }) - }) + 'X-Foo': 'Bar', + }, + }); + }); request(app) .get('/') .expect(404) .expect(utils.shouldNotHaveHeader('X-Foo')) - .end(done) - }) + .end(done); + }); describe('when headers contains Content-Disposition', function () { it('should be ignored', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/user.html', { headers: { - 'Content-Disposition': 'inline' - } - }) - }) + 'Content-Disposition': 'inline', + }, + }); + }); request(app) .get('/') .expect(200) .expect('Content-Disposition', 'attachment; filename="user.html"') - .end(done) - }) + .end(done); + }); it('should be ignored case-insensitively', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/user.html', { headers: { - 'content-disposition': 'inline' - } - }) - }) + 'content-disposition': 'inline', + }, + }); + }); request(app) .get('/') .expect(200) .expect('Content-Disposition', 'attachment; filename="user.html"') - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); describe('with "root" option', function () { it('should allow relative path', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('name.txt', { - root: FIXTURES_PATH - }) - }) + root: FIXTURES_PATH, + }); + }); request(app) .get('/') .expect(200) .expect('Content-Disposition', 'attachment; filename="name.txt"') .expect(utils.shouldHaveBody(Buffer.from('tobi'))) - .end(done) - }) + .end(done); + }); it('should allow up within root', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('fake/../name.txt', { - root: FIXTURES_PATH - }) - }) + root: FIXTURES_PATH, + }); + }); request(app) .get('/') .expect(200) .expect('Content-Disposition', 'attachment; filename="name.txt"') .expect(utils.shouldHaveBody(Buffer.from('tobi'))) - .end(done) - }) + .end(done); + }); it('should reject up outside root', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - var p = '..' + path.sep + - path.relative(path.dirname(FIXTURES_PATH), path.join(FIXTURES_PATH, 'name.txt')) + var p = + '..' + + path.sep + + path.relative( + path.dirname(FIXTURES_PATH), + path.join(FIXTURES_PATH, 'name.txt'), + ); res.download(p, { - root: FIXTURES_PATH - }) - }) + root: FIXTURES_PATH, + }); + }); request(app) .get('/') .expect(403) .expect(utils.shouldNotHaveHeader('Content-Disposition')) - .end(done) - }) + .end(done); + }); it('should reject reading outside root', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('../name.txt', { - root: FIXTURES_PATH - }) - }) + root: FIXTURES_PATH, + }); + }); request(app) .get('/') .expect(403) .expect(utils.shouldNotHaveHeader('Content-Disposition')) - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); - describe('.download(path, filename, fn)', function(){ - it('should invoke the callback', function(done){ + describe('.download(path, filename, fn)', function () { + it('should invoke the callback', function (done) { var app = express(); var cb = after(2, done); - app.use(function(req, res){ - res.download('test/fixtures/user.html', 'document', cb) + app.use(function (req, res) { + res.download('test/fixtures/user.html', 'document', cb); }); request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="document"') - .expect(200, cb); - }) - }) + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="document"') + .expect(200, cb); + }); + }); describe('.download(path, filename, options, fn)', function () { it('should invoke the callback', function (done) { - var app = express() - var cb = after(2, done) - var options = {} + var app = express(); + var cb = after(2, done); + var options = {}; app.use(function (req, res) { - res.download('test/fixtures/user.html', 'document', options, cb) - }) + res.download('test/fixtures/user.html', 'document', options, cb); + }); request(app) - .get('/') - .expect(200) - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="document"') - .end(cb) - }) + .get('/') + .expect(200) + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="document"') + .end(cb); + }); it('should allow options to res.sendFile()', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/.name', 'document', { dotfiles: 'allow', - maxAge: '4h' - }) - }) + maxAge: '4h', + }); + }); request(app) .get('/') @@ -409,73 +409,71 @@ describe('res', function(){ .expect('Content-Disposition', 'attachment; filename="document"') .expect('Cache-Control', 'public, max-age=14400') .expect(utils.shouldHaveBody(Buffer.from('tobi'))) - .end(done) - }) + .end(done); + }); describe('when options.headers contains Content-Disposition', function () { it('should be ignored', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/user.html', 'document', { headers: { 'Content-Type': 'text/x-custom', - 'Content-Disposition': 'inline' - } - }) - }) + 'Content-Disposition': 'inline', + }, + }); + }); request(app) - .get('/') - .expect(200) - .expect('Content-Type', 'text/x-custom') - .expect('Content-Disposition', 'attachment; filename="document"') - .end(done) - }) + .get('/') + .expect(200) + .expect('Content-Type', 'text/x-custom') + .expect('Content-Disposition', 'attachment; filename="document"') + .end(done); + }); it('should be ignored case-insensitively', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.download('test/fixtures/user.html', 'document', { headers: { 'content-type': 'text/x-custom', - 'content-disposition': 'inline' - } - }) - }) + 'content-disposition': 'inline', + }, + }); + }); request(app) - .get('/') - .expect(200) - .expect('Content-Type', 'text/x-custom') - .expect('Content-Disposition', 'attachment; filename="document"') - .end(done) - }) - }) - }) + .get('/') + .expect(200) + .expect('Content-Type', 'text/x-custom') + .expect('Content-Disposition', 'attachment; filename="document"') + .end(done); + }); + }); + }); - describe('on failure', function(){ - it('should invoke the callback', function(done){ + describe('on failure', function () { + it('should invoke the callback', function (done) { var app = express(); app.use(function (req, res, next) { - res.download('test/fixtures/foobar.html', function(err){ + res.download('test/fixtures/foobar.html', function (err) { if (!err) return next(new Error('expected error')); res.send('got ' + err.status + ' ' + err.code); }); }); - request(app) - .get('/') - .expect(200, 'got 404 ENOENT', done); - }) + request(app).get('/').expect(200, 'got 404 ENOENT', done); + }); - it('should remove Content-Disposition', function(done){ - var app = express() + it('should remove Content-Disposition', function (done) { + var app = express(); app.use(function (req, res, next) { - res.download('test/fixtures/foobar.html', function(err){ + res.download('test/fixtures/foobar.html', function (err) { if (!err) return next(new Error('expected error')); res.end('failed'); }); @@ -484,15 +482,15 @@ describe('res', function(){ request(app) .get('/') .expect(utils.shouldNotHaveHeader('Content-Disposition')) - .expect(200, 'failed', done) - }) - }) -}) + .expect(200, 'failed', done); + }); + }); +}); -function tryRequire (name) { +function tryRequire(name) { try { - return require(name) + return require(name); } catch (e) { - return {} + return {}; } } diff --git a/test/res.format.js b/test/res.format.js index 59205bfaf42..095643c99fe 100644 --- a/test/res.format.js +++ b/test/res.format.js @@ -1,145 +1,166 @@ -'use strict' +'use strict'; -var after = require('after') -var express = require('../') - , request = require('supertest') - , assert = require('assert'); +var after = require('after'); +var express = require('../'), + request = require('supertest'), + assert = require('assert'); var app1 = express(); -app1.use(function(req, res, next){ +app1.use(function (req, res, next) { res.format({ - 'text/plain': function(){ + 'text/plain': function () { res.send('hey'); }, - 'text/html': function(){ + 'text/html': function () { res.send('

        hey

        '); }, - 'application/json': function(a, b, c){ - assert(req === a) - assert(res === b) - assert(next === c) + 'application/json': function (a, b, c) { + assert(req === a); + assert(res === b); + assert(next === c); res.send({ message: 'hey' }); - } + }, }); }); -app1.use(function(err, req, res, next){ +app1.use(function (err, req, res, next) { if (!err.types) throw err; - res.status(err.status) - res.send('Supports: ' + err.types.join(', ')) -}) + res.status(err.status); + res.send('Supports: ' + err.types.join(', ')); +}); var app2 = express(); -app2.use(function(req, res, next){ +app2.use(function (req, res, next) { res.format({ - text: function(){ res.send('hey') }, - html: function(){ res.send('

        hey

        ') }, - json: function(){ res.send({ message: 'hey' }) } + text: function () { + res.send('hey'); + }, + html: function () { + res.send('

        hey

        '); + }, + json: function () { + res.send({ message: 'hey' }); + }, }); }); -app2.use(function(err, req, res, next){ - res.status(err.status) - res.send('Supports: ' + err.types.join(', ')) -}) +app2.use(function (err, req, res, next) { + res.status(err.status); + res.send('Supports: ' + err.types.join(', ')); +}); var app3 = express(); -app3.use(function(req, res, next){ +app3.use(function (req, res, next) { res.format({ - text: function(){ res.send('hey') }, + text: function () { + res.send('hey'); + }, default: function (a, b, c) { - assert(req === a) - assert(res === b) - assert(next === c) - res.send('default') - } - }) + assert(req === a); + assert(res === b); + assert(next === c); + res.send('default'); + }, + }); }); var app4 = express(); app4.get('/', function (req, res) { res.format({ - text: function(){ res.send('hey') }, - html: function(){ res.send('

        hey

        ') }, - json: function(){ res.send({ message: 'hey' }) } + text: function () { + res.send('hey'); + }, + html: function () { + res.send('

        hey

        '); + }, + json: function () { + res.send({ message: 'hey' }); + }, }); }); -app4.use(function(err, req, res, next){ - res.status(err.status) - res.send('Supports: ' + err.types.join(', ')) -}) +app4.use(function (err, req, res, next) { + res.status(err.status); + res.send('Supports: ' + err.types.join(', ')); +}); var app5 = express(); app5.use(function (req, res, next) { res.format({ - default: function () { res.send('hey') } + default: function () { + res.send('hey'); + }, }); }); -describe('res', function(){ - describe('.format(obj)', function(){ - describe('with canonicalized mime types', function(){ +describe('res', function () { + describe('.format(obj)', function () { + describe('with canonicalized mime types', function () { test(app1); - }) + }); - describe('with extnames', function(){ + describe('with extnames', function () { test(app2); - }) + }); - describe('with parameters', function(){ + describe('with parameters', function () { var app = express(); - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.format({ - 'text/plain; charset=utf-8': function(){ res.send('hey') }, - 'text/html; foo=bar; bar=baz': function(){ res.send('

        hey

        ') }, - 'application/json; q=0.5': function(){ res.send({ message: 'hey' }) } + 'text/plain; charset=utf-8': function () { + res.send('hey'); + }, + 'text/html; foo=bar; bar=baz': function () { + res.send('

        hey

        '); + }, + 'application/json; q=0.5': function () { + res.send({ message: 'hey' }); + }, }); }); - app.use(function(err, req, res, next){ - res.status(err.status) - res.send('Supports: ' + err.types.join(', ')) + app.use(function (err, req, res, next) { + res.status(err.status); + res.send('Supports: ' + err.types.join(', ')); }); test(app); - }) + }); - describe('given .default', function(){ - it('should be invoked instead of auto-responding', function(done){ + describe('given .default', function () { + it('should be invoked instead of auto-responding', function (done) { request(app3) - .get('/') - .set('Accept', 'text/html') - .expect('default', done); - }) + .get('/') + .set('Accept', 'text/html') + .expect('default', done); + }); it('should work when only .default is provided', function (done) { - request(app5) - .get('/') - .set('Accept', '*/*') - .expect('hey', done); - }) + request(app5).get('/').set('Accept', '*/*').expect('hey', done); + }); it('should be able to invoke other formatter', function (done) { - var app = express() + var app = express(); app.use(function (req, res, next) { res.format({ - json: function () { res.send('json') }, + json: function () { + res.send('json'); + }, default: function () { - res.header('x-default', '1') - this.json() - } - }) - }) + res.header('x-default', '1'); + this.json(); + }, + }); + }); request(app) .get('/') @@ -147,102 +168,106 @@ describe('res', function(){ .expect(200) .expect('x-default', '1') .expect('json') - .end(done) - }) - }) + .end(done); + }); + }); - describe('in router', function(){ + describe('in router', function () { test(app4); - }) + }); - describe('in router', function(){ + describe('in router', function () { var app = express(); var router = express.Router(); router.get('/', function (req, res) { res.format({ - text: function(){ res.send('hey') }, - html: function(){ res.send('

        hey

        ') }, - json: function(){ res.send({ message: 'hey' }) } + text: function () { + res.send('hey'); + }, + html: function () { + res.send('

        hey

        '); + }, + json: function () { + res.send({ message: 'hey' }); + }, }); }); - router.use(function(err, req, res, next){ - res.status(err.status) - res.send('Supports: ' + err.types.join(', ')) - }) + router.use(function (err, req, res, next) { + res.status(err.status); + res.send('Supports: ' + err.types.join(', ')); + }); - app.use(router) + app.use(router); - test(app) - }) - }) -}) + test(app); + }); + }); +}); function test(app) { - it('should utilize qvalues in negotiation', function(done){ + it('should utilize qvalues in negotiation', function (done) { request(app) - .get('/') - .set('Accept', 'text/html; q=.5, application/json, */*; q=.1') - .expect({"message":"hey"}, done); - }) + .get('/') + .set('Accept', 'text/html; q=.5, application/json, */*; q=.1') + .expect({ message: 'hey' }, done); + }); - it('should allow wildcard type/subtypes', function(done){ + it('should allow wildcard type/subtypes', function (done) { request(app) - .get('/') - .set('Accept', 'text/html; q=.5, application/*, */*; q=.1') - .expect({"message":"hey"}, done); - }) + .get('/') + .set('Accept', 'text/html; q=.5, application/*, */*; q=.1') + .expect({ message: 'hey' }, done); + }); - it('should default the Content-Type', function(done){ + it('should default the Content-Type', function (done) { request(app) - .get('/') - .set('Accept', 'text/html; q=.5, text/plain') - .expect('Content-Type', 'text/plain; charset=utf-8') - .expect('hey', done); - }) + .get('/') + .set('Accept', 'text/html; q=.5, text/plain') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect('hey', done); + }); it('should set the correct charset for the Content-Type', function (done) { - var cb = after(3, done) + var cb = after(3, done); request(app) - .get('/') - .set('Accept', 'text/html') - .expect('Content-Type', 'text/html; charset=utf-8', cb) + .get('/') + .set('Accept', 'text/html') + .expect('Content-Type', 'text/html; charset=utf-8', cb); request(app) - .get('/') - .set('Accept', 'text/plain') - .expect('Content-Type', 'text/plain; charset=utf-8', cb) + .get('/') + .set('Accept', 'text/plain') + .expect('Content-Type', 'text/plain; charset=utf-8', cb); request(app) - .get('/') - .set('Accept', 'application/json') - .expect('Content-Type', 'application/json; charset=utf-8', cb) - }) + .get('/') + .set('Accept', 'application/json') + .expect('Content-Type', 'application/json; charset=utf-8', cb); + }); - it('should Vary: Accept', function(done){ + it('should Vary: Accept', function (done) { request(app) - .get('/') - .set('Accept', 'text/html; q=.5, text/plain') - .expect('Vary', 'Accept', done); - }) - - describe('when Accept is not present', function(){ - it('should invoke the first callback', function(done){ - request(app) .get('/') - .expect('hey', done); - }) - }) + .set('Accept', 'text/html; q=.5, text/plain') + .expect('Vary', 'Accept', done); + }); + + describe('when Accept is not present', function () { + it('should invoke the first callback', function (done) { + request(app).get('/').expect('hey', done); + }); + }); - describe('when no match is made', function(){ - it('should should respond with 406 not acceptable', function(done){ + describe('when no match is made', function () { + it('should should respond with 406 not acceptable', function (done) { request(app) - .get('/') - .set('Accept', 'foo/bar') - .expect('Supports: text/plain, text/html, application/json') - .expect(406, done) - }) - }) + .get('/') + .set('Accept', 'foo/bar') + .expect('Supports: text/plain, text/html, application/json') + .expect(406, done); + }); + }); } diff --git a/test/res.get.js b/test/res.get.js index a5f12e2e539..c904dcd016a 100644 --- a/test/res.get.js +++ b/test/res.get.js @@ -1,10 +1,10 @@ -'use strict' +'use strict'; var express = require('..'); var request = require('supertest'); -describe('res', function(){ - describe('.get(field)', function(){ +describe('res', function () { + describe('.get(field)', function () { it('should get the response header field', function (done) { var app = express(); @@ -13,9 +13,7 @@ describe('res', function(){ res.send(res.get('Content-Type')); }); - request(app) - .get('/') - .expect(200, 'text/x-foo', done); - }) - }) -}) + request(app).get('/').expect(200, 'text/x-foo', done); + }); + }); +}); diff --git a/test/res.json.js b/test/res.json.js index bef8adafd53..eb4c3eaf600 100644 --- a/test/res.json.js +++ b/test/res.json.js @@ -1,186 +1,182 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest') - , assert = require('assert'); +var express = require('../'), + request = require('supertest'), + assert = require('assert'); -describe('res', function(){ - describe('.json(object)', function(){ - it('should not support jsonp callbacks', function(done){ +describe('res', function () { + describe('.json(object)', function () { + it('should not support jsonp callbacks', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.json({ foo: 'bar' }); }); - request(app) - .get('/?callback=foo') - .expect('{"foo":"bar"}', done); - }) + request(app).get('/?callback=foo').expect('{"foo":"bar"}', done); + }); - it('should not override previous Content-Types', function(done){ + it('should not override previous Content-Types', function (done) { var app = express(); - app.get('/', function(req, res){ + app.get('/', function (req, res) { res.type('application/vnd.example+json'); res.json({ hello: 'world' }); }); request(app) - .get('/') - .expect('Content-Type', 'application/vnd.example+json; charset=utf-8') - .expect(200, '{"hello":"world"}', done); - }) + .get('/') + .expect('Content-Type', 'application/vnd.example+json; charset=utf-8') + .expect(200, '{"hello":"world"}', done); + }); - describe('when given primitives', function(){ - it('should respond with json for null', function(done){ + describe('when given primitives', function () { + it('should respond with json for null', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.json(null); }); request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, 'null', done) - }) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, 'null', done); + }); - it('should respond with json for Number', function(done){ + it('should respond with json for Number', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.json(300); }); request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '300', done) - }) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '300', done); + }); - it('should respond with json for String', function(done){ + it('should respond with json for String', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.json('str'); }); request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '"str"', done) - }) - }) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '"str"', done); + }); + }); - describe('when given an array', function(){ - it('should respond with json', function(done){ + describe('when given an array', function () { + it('should respond with json', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.json(['foo', 'bar', 'baz']); }); request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '["foo","bar","baz"]', done) - }) - }) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '["foo","bar","baz"]', done); + }); + }); - describe('when given an object', function(){ - it('should respond with json', function(done){ + describe('when given an object', function () { + it('should respond with json', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.json({ name: 'tobi' }); }); request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '{"name":"tobi"}', done) - }) - }) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '{"name":"tobi"}', done); + }); + }); describe('"json escape" setting', function () { it('should be undefined by default', function () { - var app = express() - assert.strictEqual(app.get('json escape'), undefined) - }) + var app = express(); + assert.strictEqual(app.get('json escape'), undefined); + }); it('should unicode escape HTML-sniffing characters', function (done) { - var app = express() + var app = express(); - app.enable('json escape') + app.enable('json escape'); app.use(function (req, res) { - res.json({ '&': ''); + app.use(function (req, res) { + res.redirect( + 'http://example.com/?param=', + ); }); request(app) - .get('/') - .set('Host', 'http://example.com') - .set('Accept', 'text/plain, */*') - .expect('Content-Type', /plain/) - .expect('Location', 'http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E') - .expect(302, 'Found. Redirecting to http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E', done) - }) - - it('should include the redirect type', function(done){ + .get('/') + .set('Host', 'http://example.com') + .set('Accept', 'text/plain, */*') + .expect('Content-Type', /plain/) + .expect( + 'Location', + 'http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E', + ) + .expect( + 302, + 'Found. Redirecting to http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E', + done, + ); + }); + + it('should include the redirect type', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.redirect(301, 'http://google.com'); }); request(app) - .get('/') - .set('Accept', 'text/plain, */*') - .expect('Content-Type', /plain/) - .expect('Location', 'http://google.com') - .expect(301, 'Moved Permanently. Redirecting to http://google.com', done); - }) - }) - - describe('when accepting neither text or html', function(){ - it('should respond with an empty body', function(done){ + .get('/') + .set('Accept', 'text/plain, */*') + .expect('Content-Type', /plain/) + .expect('Location', 'http://google.com') + .expect( + 301, + 'Moved Permanently. Redirecting to http://google.com', + done, + ); + }); + }); + + describe('when accepting neither text or html', function () { + it('should respond with an empty body', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.redirect('http://google.com'); }); @@ -208,7 +226,7 @@ describe('res', function(){ .expect('content-length', '0') .expect(utils.shouldNotHaveHeader('Content-Type')) .expect(utils.shouldNotHaveBody()) - .end(done) - }) - }) -}) + .end(done); + }); + }); +}); diff --git a/test/res.render.js b/test/res.render.js index 50f0b0a7425..626bb9295f3 100644 --- a/test/res.render.js +++ b/test/res.render.js @@ -1,309 +1,277 @@ -'use strict' +'use strict'; var express = require('..'); -var path = require('path') +var path = require('path'); var request = require('supertest'); var tmpl = require('./support/tmpl'); -describe('res', function(){ - describe('.render(name)', function(){ - it('should support absolute paths', function(done){ +describe('res', function () { + describe('.render(name)', function () { + it('should support absolute paths', function (done) { var app = createApp(); app.locals.user = { name: 'tobi' }; - app.use(function(req, res){ - res.render(path.join(__dirname, 'fixtures', 'user.tmpl')) + app.use(function (req, res) { + res.render(path.join(__dirname, 'fixtures', 'user.tmpl')); }); - request(app) - .get('/') - .expect('

        tobi

        ', done); - }) + request(app).get('/').expect('

        tobi

        ', done); + }); - it('should support absolute paths with "view engine"', function(done){ + it('should support absolute paths with "view engine"', function (done) { var app = createApp(); app.locals.user = { name: 'tobi' }; app.set('view engine', 'tmpl'); - app.use(function(req, res){ - res.render(path.join(__dirname, 'fixtures', 'user')) + app.use(function (req, res) { + res.render(path.join(__dirname, 'fixtures', 'user')); }); - request(app) - .get('/') - .expect('

        tobi

        ', done); - }) + request(app).get('/').expect('

        tobi

        ', done); + }); it('should error without "view engine" set and file extension to a non-engine module', function (done) { - var app = createApp() + var app = createApp(); - app.locals.user = { name: 'tobi' } + app.locals.user = { name: 'tobi' }; app.use(function (req, res) { - res.render(path.join(__dirname, 'fixtures', 'broken.send')) - }) + res.render(path.join(__dirname, 'fixtures', 'broken.send')); + }); request(app) - .get('/') - .expect(500, /does not provide a view engine/, done) - }) + .get('/') + .expect(500, /does not provide a view engine/, done); + }); it('should error without "view engine" set and no file extension', function (done) { var app = createApp(); app.locals.user = { name: 'tobi' }; - app.use(function(req, res){ - res.render(path.join(__dirname, 'fixtures', 'user')) + app.use(function (req, res) { + res.render(path.join(__dirname, 'fixtures', 'user')); }); request(app) - .get('/') - .expect(500, /No default engine was specified/, done); - }) + .get('/') + .expect(500, /No default engine was specified/, done); + }); - it('should expose app.locals', function(done){ + it('should expose app.locals', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.locals.user = { name: 'tobi' }; - app.use(function(req, res){ + app.use(function (req, res) { res.render('user.tmpl'); }); - request(app) - .get('/') - .expect('

        tobi

        ', done); - }) + request(app).get('/').expect('

        tobi

        ', done); + }); - it('should expose app.locals with `name` property', function(done){ + it('should expose app.locals with `name` property', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.locals.name = 'tobi'; - app.use(function(req, res){ + app.use(function (req, res) { res.render('name.tmpl'); }); - request(app) - .get('/') - .expect('

        tobi

        ', done); - }) + request(app).get('/').expect('

        tobi

        ', done); + }); - it('should support index.', function(done){ + it('should support index.', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.set('view engine', 'tmpl'); - app.use(function(req, res){ + app.use(function (req, res) { res.render('blog/post'); }); - request(app) - .get('/') - .expect('

        blog post

        ', done); - }) + request(app).get('/').expect('

        blog post

        ', done); + }); - describe('when an error occurs', function(){ - it('should next(err)', function(done){ + describe('when an error occurs', function () { + it('should next(err)', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); - app.use(function(req, res){ + app.use(function (req, res) { res.render('user.tmpl'); }); - app.use(function(err, req, res, next){ - res.status(500).send('got error: ' + err.name) + app.use(function (err, req, res, next) { + res.status(500).send('got error: ' + err.name); }); - request(app) - .get('/') - .expect(500, 'got error: RenderError', done) - }) - }) + request(app).get('/').expect(500, 'got error: RenderError', done); + }); + }); - describe('when "view engine" is given', function(){ - it('should render the template', function(done){ + describe('when "view engine" is given', function () { + it('should render the template', function (done) { var app = createApp(); app.set('view engine', 'tmpl'); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); - app.use(function(req, res){ + app.use(function (req, res) { res.render('email'); }); - request(app) - .get('/') - .expect('

        This is an email

        ', done); - }) - }) + request(app).get('/').expect('

        This is an email

        ', done); + }); + }); - describe('when "views" is given', function(){ - it('should lookup the file in the path', function(done){ + describe('when "views" is given', function () { + it('should lookup the file in the path', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures', 'default_layout')) + app.set('views', path.join(__dirname, 'fixtures', 'default_layout')); - app.use(function(req, res){ + app.use(function (req, res) { res.render('user.tmpl', { user: { name: 'tobi' } }); }); - request(app) - .get('/') - .expect('

        tobi

        ', done); - }) + request(app).get('/').expect('

        tobi

        ', done); + }); - describe('when array of paths', function(){ - it('should lookup the file in the path', function(done){ + describe('when array of paths', function () { + it('should lookup the file in the path', function (done) { var app = createApp(); var views = [ path.join(__dirname, 'fixtures', 'local_layout'), - path.join(__dirname, 'fixtures', 'default_layout') - ] + path.join(__dirname, 'fixtures', 'default_layout'), + ]; app.set('views', views); - app.use(function(req, res){ + app.use(function (req, res) { res.render('user.tmpl', { user: { name: 'tobi' } }); }); - request(app) - .get('/') - .expect('tobi', done); - }) + request(app).get('/').expect('tobi', done); + }); - it('should lookup in later paths until found', function(done){ + it('should lookup in later paths until found', function (done) { var app = createApp(); var views = [ path.join(__dirname, 'fixtures', 'local_layout'), - path.join(__dirname, 'fixtures', 'default_layout') - ] + path.join(__dirname, 'fixtures', 'default_layout'), + ]; app.set('views', views); - app.use(function(req, res){ + app.use(function (req, res) { res.render('name.tmpl', { name: 'tobi' }); }); - request(app) - .get('/') - .expect('

        tobi

        ', done); - }) - }) - }) - }) + request(app).get('/').expect('

        tobi

        ', done); + }); + }); + }); + }); - describe('.render(name, option)', function(){ - it('should render the template', function(done){ + describe('.render(name, option)', function () { + it('should render the template', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); var user = { name: 'tobi' }; - app.use(function(req, res){ + app.use(function (req, res) { res.render('user.tmpl', { user: user }); }); - request(app) - .get('/') - .expect('

        tobi

        ', done); - }) + request(app).get('/').expect('

        tobi

        ', done); + }); - it('should expose app.locals', function(done){ + it('should expose app.locals', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.locals.user = { name: 'tobi' }; - app.use(function(req, res){ + app.use(function (req, res) { res.render('user.tmpl'); }); - request(app) - .get('/') - .expect('

        tobi

        ', done); - }) + request(app).get('/').expect('

        tobi

        ', done); + }); - it('should expose res.locals', function(done){ + it('should expose res.locals', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); - app.use(function(req, res){ + app.use(function (req, res) { res.locals.user = { name: 'tobi' }; res.render('user.tmpl'); }); - request(app) - .get('/') - .expect('

        tobi

        ', done); - }) + request(app).get('/').expect('

        tobi

        ', done); + }); - it('should give precedence to res.locals over app.locals', function(done){ + it('should give precedence to res.locals over app.locals', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.locals.user = { name: 'tobi' }; - app.use(function(req, res){ + app.use(function (req, res) { res.locals.user = { name: 'jane' }; res.render('user.tmpl', {}); }); - request(app) - .get('/') - .expect('

        jane

        ', done); - }) + request(app).get('/').expect('

        jane

        ', done); + }); - it('should give precedence to res.render() locals over res.locals', function(done){ + it('should give precedence to res.render() locals over res.locals', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); var jane = { name: 'jane' }; - app.use(function(req, res){ + app.use(function (req, res) { res.locals.user = { name: 'tobi' }; res.render('user.tmpl', { user: jane }); }); - request(app) - .get('/') - .expect('

        jane

        ', done); - }) + request(app).get('/').expect('

        jane

        ', done); + }); - it('should give precedence to res.render() locals over app.locals', function(done){ + it('should give precedence to res.render() locals over app.locals', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); app.locals.user = { name: 'tobi' }; var jane = { name: 'jane' }; - app.use(function(req, res){ + app.use(function (req, res) { res.render('user.tmpl', { user: jane }); }); - request(app) - .get('/') - .expect('

        jane

        ', done); - }) - }) + request(app).get('/').expect('

        jane

        ', done); + }); + }); - describe('.render(name, options, fn)', function(){ - it('should pass the resulting string', function(done){ + describe('.render(name, options, fn)', function () { + it('should pass the resulting string', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); - app.use(function(req, res){ + app.use(function (req, res) { var tobi = { name: 'tobi' }; res.render('user.tmpl', { user: tobi }, function (err, html) { html = html.replace('tobi', 'loki'); @@ -311,19 +279,17 @@ describe('res', function(){ }); }); - request(app) - .get('/') - .expect('

        loki

        ', done); - }) - }) + request(app).get('/').expect('

        loki

        ', done); + }); + }); - describe('.render(name, fn)', function(){ - it('should pass the resulting string', function(done){ + describe('.render(name, fn)', function () { + it('should pass the resulting string', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); - app.use(function(req, res){ + app.use(function (req, res) { res.locals.user = { name: 'tobi' }; res.render('user.tmpl', function (err, html) { html = html.replace('tobi', 'loki'); @@ -331,32 +297,28 @@ describe('res', function(){ }); }); - request(app) - .get('/') - .expect('

        loki

        ', done); - }) + request(app).get('/').expect('

        loki

        ', done); + }); - describe('when an error occurs', function(){ - it('should pass it to the callback', function(done){ + describe('when an error occurs', function () { + it('should pass it to the callback', function (done) { var app = createApp(); - app.set('views', path.join(__dirname, 'fixtures')) + app.set('views', path.join(__dirname, 'fixtures')); - app.use(function(req, res){ + app.use(function (req, res) { res.render('user.tmpl', function (err) { if (err) { - res.status(500).send('got error: ' + err.name) + res.status(500).send('got error: ' + err.name); } }); }); - request(app) - .get('/') - .expect(500, 'got error: RenderError', done) - }) - }) - }) -}) + request(app).get('/').expect(500, 'got error: RenderError', done); + }); + }); + }); +}); function createApp() { var app = express(); diff --git a/test/res.send.js b/test/res.send.js index bce62c8d406..8f727fc928d 100644 --- a/test/res.send.js +++ b/test/res.send.js @@ -1,86 +1,79 @@ -'use strict' +'use strict'; -var assert = require('assert') -var Buffer = require('safe-buffer').Buffer +var assert = require('assert'); +var Buffer = require('safe-buffer').Buffer; var express = require('..'); var methods = require('methods'); var request = require('supertest'); var utils = require('./support/utils'); -var shouldSkipQuery = require('./support/utils').shouldSkipQuery +var shouldSkipQuery = require('./support/utils').shouldSkipQuery; -describe('res', function(){ - describe('.send()', function(){ - it('should set body to ""', function(done){ +describe('res', function () { + describe('.send()', function () { + it('should set body to ""', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send(); }); - request(app) - .get('/') - .expect(200, '', done); - }) - }) + request(app).get('/').expect(200, '', done); + }); + }); - describe('.send(null)', function(){ - it('should set body to ""', function(done){ + describe('.send(null)', function () { + it('should set body to ""', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send(null); }); - request(app) - .get('/') - .expect('Content-Length', '0') - .expect(200, '', done); - }) - }) + request(app).get('/').expect('Content-Length', '0').expect(200, '', done); + }); + }); - describe('.send(undefined)', function(){ - it('should set body to ""', function(done){ + describe('.send(undefined)', function () { + it('should set body to ""', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send(undefined); }); - request(app) - .get('/') - .expect(200, '', done); - }) - }) + request(app).get('/').expect(200, '', done); + }); + }); - describe('.send(Number)', function(){ - it('should send as application/json', function(done){ + describe('.send(Number)', function () { + it('should send as application/json', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send(1000); }); request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '1000', done) - }) - }) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '1000', done); + }); + }); - describe('.send(String)', function(){ - it('should send as html', function(done){ + describe('.send(String)', function () { + it('should send as html', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send('

        hey

        '); }); request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect(200, '

        hey

        ', done); - }) + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect(200, '

        hey

        ', done); + }); it('should set ETag', function (done) { var app = express(); @@ -91,57 +84,59 @@ describe('res', function(){ }); request(app) - .get('/') - .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') - .expect(200, done); - }) + .get('/') + .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') + .expect(200, done); + }); - it('should not override Content-Type', function(done){ + it('should not override Content-Type', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.set('Content-Type', 'text/plain').send('hey'); }); request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=utf-8') - .expect(200, 'hey', done); - }) + .get('/') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200, 'hey', done); + }); - it('should override charset in Content-Type', function(done){ + it('should override charset in Content-Type', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.set('Content-Type', 'text/plain; charset=iso-8859-1').send('hey'); }); request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=utf-8') - .expect(200, 'hey', done); - }) + .get('/') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200, 'hey', done); + }); - it('should keep charset in Content-Type for Buffers', function(done){ + it('should keep charset in Content-Type for Buffers', function (done) { var app = express(); - app.use(function(req, res){ - res.set('Content-Type', 'text/plain; charset=iso-8859-1').send(Buffer.from('hi')) + app.use(function (req, res) { + res + .set('Content-Type', 'text/plain; charset=iso-8859-1') + .send(Buffer.from('hi')); }); request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=iso-8859-1') - .expect(200, 'hi', done); - }) - }) + .get('/') + .expect('Content-Type', 'text/plain; charset=iso-8859-1') + .expect(200, 'hi', done); + }); + }); - describe('.send(Buffer)', function(){ - it('should send as octet-stream', function(done){ + describe('.send(Buffer)', function () { + it('should send as octet-stream', function (done) { var app = express(); - app.use(function(req, res){ - res.send(Buffer.from('hello')) + app.use(function (req, res) { + res.send(Buffer.from('hello')); }); request(app) @@ -149,69 +144,66 @@ describe('res', function(){ .expect(200) .expect('Content-Type', 'application/octet-stream') .expect(utils.shouldHaveBody(Buffer.from('hello'))) - .end(done) - }) + .end(done); + }); it('should set ETag', function (done) { var app = express(); app.use(function (req, res) { - res.send(Buffer.alloc(999, '-')) + res.send(Buffer.alloc(999, '-')); }); request(app) - .get('/') - .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') - .expect(200, done); - }) + .get('/') + .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') + .expect(200, done); + }); - it('should not override Content-Type', function(done){ + it('should not override Content-Type', function (done) { var app = express(); - app.use(function(req, res){ - res.set('Content-Type', 'text/plain').send(Buffer.from('hey')) + app.use(function (req, res) { + res.set('Content-Type', 'text/plain').send(Buffer.from('hey')); }); request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=utf-8') - .expect(200, 'hey', done); - }) + .get('/') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200, 'hey', done); + }); it('should not override ETag', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.type('text/plain').set('ETag', '"foo"').send(Buffer.from('hey')) - }) + res.type('text/plain').set('ETag', '"foo"').send(Buffer.from('hey')); + }); - request(app) - .get('/') - .expect('ETag', '"foo"') - .expect(200, 'hey', done) - }) - }) + request(app).get('/').expect('ETag', '"foo"').expect(200, 'hey', done); + }); + }); - describe('.send(Object)', function(){ - it('should send as application/json', function(done){ + describe('.send(Object)', function () { + it('should send as application/json', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send({ name: 'tobi' }); }); request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '{"name":"tobi"}', done) - }) - }) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '{"name":"tobi"}', done); + }); + }); - describe('when the request method is HEAD', function(){ - it('should ignore the body', function(done){ + describe('when the request method is HEAD', function () { + it('should ignore the body', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send('yay'); }); @@ -219,131 +211,121 @@ describe('res', function(){ .head('/') .expect(200) .expect(utils.shouldNotHaveBody()) - .end(done) - }) - }) + .end(done); + }); + }); - describe('when .statusCode is 204', function(){ - it('should strip Content-* fields, Transfer-Encoding field, and body', function(done){ + describe('when .statusCode is 204', function () { + it('should strip Content-* fields, Transfer-Encoding field, and body', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.status(204).set('Transfer-Encoding', 'chunked').send('foo'); }); request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('Content-Type')) - .expect(utils.shouldNotHaveHeader('Content-Length')) - .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) - .expect(204, '', done); - }) - }) + .get('/') + .expect(utils.shouldNotHaveHeader('Content-Type')) + .expect(utils.shouldNotHaveHeader('Content-Length')) + .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) + .expect(204, '', done); + }); + }); describe('when .statusCode is 205', function () { it('should strip Transfer-Encoding field and body, set Content-Length', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.status(205).set('Transfer-Encoding', 'chunked').send('foo') - }) + res.status(205).set('Transfer-Encoding', 'chunked').send('foo'); + }); request(app) .get('/') .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) .expect('Content-Length', '0') - .expect(205, '', done) - }) - }) + .expect(205, '', done); + }); + }); - describe('when .statusCode is 304', function(){ - it('should strip Content-* fields, Transfer-Encoding field, and body', function(done){ + describe('when .statusCode is 304', function () { + it('should strip Content-* fields, Transfer-Encoding field, and body', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.status(304).set('Transfer-Encoding', 'chunked').send('foo'); }); request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('Content-Type')) - .expect(utils.shouldNotHaveHeader('Content-Length')) - .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) - .expect(304, '', done); - }) - }) - - it('should always check regardless of length', function(done){ + .get('/') + .expect(utils.shouldNotHaveHeader('Content-Type')) + .expect(utils.shouldNotHaveHeader('Content-Length')) + .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) + .expect(304, '', done); + }); + }); + + it('should always check regardless of length', function (done) { var app = express(); var etag = '"asdf"'; - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.set('ETag', etag); res.send('hey'); }); - request(app) - .get('/') - .set('If-None-Match', etag) - .expect(304, done); - }) + request(app).get('/').set('If-None-Match', etag).expect(304, done); + }); - it('should respond with 304 Not Modified when fresh', function(done){ + it('should respond with 304 Not Modified when fresh', function (done) { var app = express(); var etag = '"asdf"'; - app.use(function(req, res){ + app.use(function (req, res) { var str = Array(1000).join('-'); res.set('ETag', etag); res.send(str); }); - request(app) - .get('/') - .set('If-None-Match', etag) - .expect(304, done); - }) + request(app).get('/').set('If-None-Match', etag).expect(304, done); + }); - it('should not perform freshness check unless 2xx or 304', function(done){ + it('should not perform freshness check unless 2xx or 304', function (done) { var app = express(); var etag = '"asdf"'; - app.use(function(req, res, next){ + app.use(function (req, res, next) { res.status(500); res.set('ETag', etag); res.send('hey'); }); request(app) - .get('/') - .set('If-None-Match', etag) - .expect('hey') - .expect(500, done); - }) + .get('/') + .set('If-None-Match', etag) + .expect('hey') + .expect(500, done); + }); - it('should not support jsonp callbacks', function(done){ + it('should not support jsonp callbacks', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.send({ foo: 'bar' }); }); - request(app) - .get('/?callback=foo') - .expect('{"foo":"bar"}', done); - }) + request(app).get('/?callback=foo').expect('{"foo":"bar"}', done); + }); it('should be chainable', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - assert.equal(res.send('hey'), res) - }) + assert.equal(res.send('hey'), res); + }); - request(app) - .get('/') - .expect(200, 'hey', done) - }) + request(app).get('/').expect(200, 'hey', done); + }); describe('"etag" setting', function () { describe('when enabled', function () { @@ -357,29 +339,34 @@ describe('res', function(){ app.enable('etag'); request(app) - .get('/') - .expect('ETag', 'W/"c-IgR/L5SF7CJQff4wxKGF/vfPuZ0"') - .expect(200, done); + .get('/') + .expect('ETag', 'W/"c-IgR/L5SF7CJQff4wxKGF/vfPuZ0"') + .expect(200, done); }); methods.forEach(function (method) { if (method === 'connect') return; - it('should send ETag in response to ' + method.toUpperCase() + ' request', function (done) { - if (method === 'query' && shouldSkipQuery(process.versions.node)) { - this.skip() - } - var app = express(); - - app[method]('/', function (req, res) { - res.send('kajdslfkasdf'); - }); - - request(app) - [method]('/') - .expect('ETag', 'W/"c-IgR/L5SF7CJQff4wxKGF/vfPuZ0"') - .expect(200, done); - }) + it( + 'should send ETag in response to ' + + method.toUpperCase() + + ' request', + function (done) { + if (method === 'query' && shouldSkipQuery(process.versions.node)) { + this.skip(); + } + var app = express(); + + app[method]('/', function (req, res) { + res.send('kajdslfkasdf'); + }); + + request(app) + [method]('/') + .expect('ETag', 'W/"c-IgR/L5SF7CJQff4wxKGF/vfPuZ0"') + .expect(200, done); + }, + ); }); it('should send ETag for empty string response', function (done) { @@ -392,10 +379,10 @@ describe('res', function(){ app.enable('etag'); request(app) - .get('/') - .expect('ETag', 'W/"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"') - .expect(200, done); - }) + .get('/') + .expect('ETag', 'W/"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"') + .expect(200, done); + }); it('should send ETag for long response', function (done) { var app = express(); @@ -408,9 +395,9 @@ describe('res', function(){ app.enable('etag'); request(app) - .get('/') - .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') - .expect(200, done); + .get('/') + .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') + .expect(200, done); }); it('should not override ETag when manually set', function (done) { @@ -423,10 +410,7 @@ describe('res', function(){ app.enable('etag'); - request(app) - .get('/') - .expect('ETag', '"asdf"') - .expect(200, done); + request(app).get('/').expect('ETag', '"asdf"').expect(200, done); }); it('should not send ETag for res.send()', function (done) { @@ -439,10 +423,10 @@ describe('res', function(){ app.enable('etag'); request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('ETag')) - .expect(200, done); - }) + .get('/') + .expect(utils.shouldNotHaveHeader('ETag')) + .expect(200, done); + }); }); describe('when disabled', function () { @@ -457,9 +441,9 @@ describe('res', function(){ app.disable('etag'); request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('ETag')) - .expect(200, done); + .get('/') + .expect(utils.shouldNotHaveHeader('ETag')) + .expect(200, done); }); it('should send ETag when manually set', function (done) { @@ -472,10 +456,7 @@ describe('res', function(){ res.send('hello!'); }); - request(app) - .get('/') - .expect('ETag', '"asdf"') - .expect(200, done); + request(app).get('/').expect('ETag', '"asdf"').expect(200, done); }); }); @@ -490,11 +471,11 @@ describe('res', function(){ }); request(app) - .get('/') - .expect('ETag', '"d-HwnTDHB9U/PRbFMN1z1wps51lqk"') - .expect(200, done); - }) - }) + .get('/') + .expect('ETag', '"d-HwnTDHB9U/PRbFMN1z1wps51lqk"') + .expect(200, done); + }); + }); describe('when "weak"', function () { it('should send weak ETag', function (done) { @@ -507,11 +488,11 @@ describe('res', function(){ }); request(app) - .get('/') - .expect('ETag', 'W/"d-HwnTDHB9U/PRbFMN1z1wps51lqk"') - .expect(200, done) - }) - }) + .get('/') + .expect('ETag', 'W/"d-HwnTDHB9U/PRbFMN1z1wps51lqk"') + .expect(200, done); + }); + }); describe('when a function', function () { it('should send custom ETag', function (done) { @@ -521,7 +502,7 @@ describe('res', function(){ var chunk = !Buffer.isBuffer(body) ? Buffer.from(body, encoding) : body; - assert.strictEqual(chunk.toString(), 'hello, world!') + assert.strictEqual(chunk.toString(), 'hello, world!'); return '"custom"'; }); @@ -529,11 +510,8 @@ describe('res', function(){ res.send('hello, world!'); }); - request(app) - .get('/') - .expect('ETag', '"custom"') - .expect(200, done); - }) + request(app).get('/').expect('ETag', '"custom"').expect(200, done); + }); it('should not send falsy ETag', function (done) { var app = express(); @@ -547,10 +525,10 @@ describe('res', function(){ }); request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('ETag')) - .expect(200, done); - }) - }) - }) -}) + .get('/') + .expect(utils.shouldNotHaveHeader('ETag')) + .expect(200, done); + }); + }); + }); +}); diff --git a/test/res.sendFile.js b/test/res.sendFile.js index 7bba9cd6d13..d58099850ce 100644 --- a/test/res.sendFile.js +++ b/test/res.sendFile.js @@ -1,93 +1,83 @@ -'use strict' +'use strict'; var after = require('after'); -var assert = require('assert') -var asyncHooks = tryRequire('async_hooks') -var Buffer = require('safe-buffer').Buffer -var express = require('../') - , request = require('supertest') +var assert = require('assert'); +var asyncHooks = tryRequire('async_hooks'); +var Buffer = require('safe-buffer').Buffer; +var express = require('../'), + request = require('supertest'); var onFinished = require('on-finished'); var path = require('path'); var fixtures = path.join(__dirname, 'fixtures'); var utils = require('./support/utils'); -var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function' - ? describe - : describe.skip +var describeAsyncHooks = + typeof asyncHooks.AsyncLocalStorage === 'function' ? describe : describe.skip; -describe('res', function(){ +describe('res', function () { describe('.sendFile(path)', function () { it('should error missing path', function (done) { var app = createApp(); request(app) - .get('/') - .expect(500, /path.*required/, done); + .get('/') + .expect(500, /path.*required/, done); }); it('should error for non-string path', function (done) { - var app = createApp(42) + var app = createApp(42); request(app) - .get('/') - .expect(500, /TypeError: path must be a string to res.sendFile/, done) - }) + .get('/') + .expect(500, /TypeError: path must be a string to res.sendFile/, done); + }); it('should error for non-absolute path', function (done) { - var app = createApp('name.txt') + var app = createApp('name.txt'); request(app) .get('/') - .expect(500, /TypeError: path must be absolute/, done) - }) + .expect(500, /TypeError: path must be absolute/, done); + }); it('should transfer a file', function (done) { var app = createApp(path.resolve(fixtures, 'name.txt')); - request(app) - .get('/') - .expect(200, 'tobi', done); + request(app).get('/').expect(200, 'tobi', done); }); it('should transfer a file with special characters in string', function (done) { var app = createApp(path.resolve(fixtures, '% of dogs.txt')); - request(app) - .get('/') - .expect(200, '20%', done); + request(app).get('/').expect(200, '20%', done); }); it('should include ETag', function (done) { var app = createApp(path.resolve(fixtures, 'name.txt')); request(app) - .get('/') - .expect('ETag', /^(?:W\/)?"[^"]+"$/) - .expect(200, 'tobi', done); + .get('/') + .expect('ETag', /^(?:W\/)?"[^"]+"$/) + .expect(200, 'tobi', done); }); it('should 304 when ETag matches', function (done) { var app = createApp(path.resolve(fixtures, 'name.txt')); request(app) - .get('/') - .expect('ETag', /^(?:W\/)?"[^"]+"$/) - .expect(200, 'tobi', function (err, res) { - if (err) return done(err); - var etag = res.headers.etag; - request(app) .get('/') - .set('If-None-Match', etag) - .expect(304, done); - }); + .expect('ETag', /^(?:W\/)?"[^"]+"$/) + .expect(200, 'tobi', function (err, res) { + if (err) return done(err); + var etag = res.headers.etag; + request(app).get('/').set('If-None-Match', etag).expect(304, done); + }); }); it('should 404 for directory', function (done) { var app = createApp(path.resolve(fixtures, 'blog')); - request(app) - .get('/') - .expect(404, done); + request(app).get('/').expect(404, done); }); it('should 404 when not found', function (done) { @@ -98,27 +88,23 @@ describe('res', function(){ res.send('no!'); }); - request(app) - .get('/') - .expect(404, done); + request(app).get('/').expect(404, done); }); it('should send cache-control by default', function (done) { - var app = createApp(path.resolve(__dirname, 'fixtures/name.txt')) + var app = createApp(path.resolve(__dirname, 'fixtures/name.txt')); request(app) .get('/') .expect('Cache-Control', 'public, max-age=0') - .expect(200, done) - }) + .expect(200, done); + }); it('should not serve dotfiles by default', function (done) { - var app = createApp(path.resolve(__dirname, 'fixtures/.name')) + var app = createApp(path.resolve(__dirname, 'fixtures/.name')); - request(app) - .get('/') - .expect(404, done) - }) + request(app).get('/').expect(404, done); + }); it('should not override manual content-types', function (done) { var app = express(); @@ -129,95 +115,93 @@ describe('res', function(){ }); request(app) - .get('/') - .expect('Content-Type', 'application/x-bogus') - .end(done); - }) + .get('/') + .expect('Content-Type', 'application/x-bogus') + .end(done); + }); it('should not error if the client aborts', function (done) { var app = express(); - var cb = after(2, done) - var error = null + var cb = after(2, done); + var error = null; app.use(function (req, res) { setImmediate(function () { res.sendFile(path.resolve(fixtures, 'name.txt')); setTimeout(function () { - cb(error) - }, 10) - }) - test.req.abort() + cb(error); + }, 10); + }); + test.req.abort(); }); app.use(function (err, req, res, next) { - error = err - next(err) + error = err; + next(err); }); - var server = app.listen() - var test = request(server).get('/') + var server = app.listen(); + var test = request(server).get('/'); test.end(function (err) { - assert.ok(err) - server.close(cb) - }) - }) - }) + assert.ok(err); + server.close(cb); + }); + }); + }); describe('.sendFile(path, fn)', function () { it('should invoke the callback when complete', function (done) { var cb = after(2, done); var app = createApp(path.resolve(fixtures, 'name.txt'), cb); - request(app) - .get('/') - .expect(200, cb); - }) + request(app).get('/').expect(200, cb); + }); it('should invoke the callback when client aborts', function (done) { - var cb = after(2, done) + var cb = after(2, done); var app = express(); app.use(function (req, res) { setImmediate(function () { res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) { - assert.ok(err) - assert.strictEqual(err.code, 'ECONNABORTED') - cb() + assert.ok(err); + assert.strictEqual(err.code, 'ECONNABORTED'); + cb(); }); }); - test.req.abort() + test.req.abort(); }); - var server = app.listen() - var test = request(server).get('/') + var server = app.listen(); + var test = request(server).get('/'); test.end(function (err) { - assert.ok(err) - server.close(cb) - }) - }) + assert.ok(err); + server.close(cb); + }); + }); it('should invoke the callback when client already aborted', function (done) { - var cb = after(2, done) + var cb = after(2, done); var app = express(); app.use(function (req, res) { onFinished(res, function () { res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) { - assert.ok(err) - assert.strictEqual(err.code, 'ECONNABORTED') - cb() + assert.ok(err); + assert.strictEqual(err.code, 'ECONNABORTED'); + cb(); }); }); - test.req.abort() + test.req.abort(); }); - var server = app.listen() - var test = request(server).get('/') + var server = app.listen(); + var test = request(server).get('/'); test.end(function (err) { - assert.ok(err) - server.close(cb) - }) - }) + assert.ok(err); + server.close(cb); + }); + }); it('should invoke the callback without error when HEAD', function (done) { var app = express(); @@ -227,9 +211,7 @@ describe('res', function(){ res.sendFile(path.resolve(fixtures, 'name.txt'), cb); }); - request(app) - .head('/') - .expect(200, cb); + request(app).head('/').expect(200, cb); }); it('should invoke the callback without error when 304', function (done) { @@ -241,656 +223,658 @@ describe('res', function(){ }); request(app) - .get('/') - .expect('ETag', /^(?:W\/)?"[^"]+"$/) - .expect(200, 'tobi', function (err, res) { - if (err) return cb(err); - var etag = res.headers.etag; - request(app) .get('/') - .set('If-None-Match', etag) - .expect(304, cb); - }); + .expect('ETag', /^(?:W\/)?"[^"]+"$/) + .expect(200, 'tobi', function (err, res) { + if (err) return cb(err); + var etag = res.headers.etag; + request(app).get('/').set('If-None-Match', etag).expect(304, cb); + }); }); - it('should invoke the callback on 404', function(done){ + it('should invoke the callback on 404', function (done) { var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) { - res.send(err ? 'got ' + err.status + ' error' : 'no error') + res.send(err ? 'got ' + err.status + ' error' : 'no error'); }); }); - request(app) - .get('/') - .expect(200, 'got 404 error', done) - }) + request(app).get('/').expect(200, 'got 404 error', done); + }); describeAsyncHooks('async local storage', function () { it('should presist store', function (done) { - var app = express() - var cb = after(2, done) - var store = { foo: 'bar' } + var app = express(); + var cb = after(2, done); + var store = { foo: 'bar' }; app.use(function (req, res, next) { - req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage() - req.asyncLocalStorage.run(store, next) - }) + req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage(); + req.asyncLocalStorage.run(store, next); + }); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) { - if (err) return cb(err) + if (err) return cb(err); - var local = req.asyncLocalStorage.getStore() + var local = req.asyncLocalStorage.getStore(); - assert.strictEqual(local.foo, 'bar') - cb() - }) - }) + assert.strictEqual(local.foo, 'bar'); + cb(); + }); + }); request(app) .get('/') .expect('Content-Type', 'text/plain; charset=utf-8') - .expect(200, 'tobi', cb) - }) + .expect(200, 'tobi', cb); + }); it('should presist store on error', function (done) { - var app = express() - var store = { foo: 'bar' } + var app = express(); + var store = { foo: 'bar' }; app.use(function (req, res, next) { - req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage() - req.asyncLocalStorage.run(store, next) - }) + req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage(); + req.asyncLocalStorage.run(store, next); + }); app.use(function (req, res) { - res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) { - var local = req.asyncLocalStorage.getStore() - - if (local) { - res.setHeader('x-store-foo', String(local.foo)) - } - - res.send(err ? 'got ' + err.status + ' error' : 'no error') - }) - }) + res.sendFile( + path.resolve(fixtures, 'does-not-exist'), + function (err) { + var local = req.asyncLocalStorage.getStore(); + + if (local) { + res.setHeader('x-store-foo', String(local.foo)); + } + + res.send(err ? 'got ' + err.status + ' error' : 'no error'); + }, + ); + }); request(app) .get('/') .expect(200) .expect('x-store-foo', 'bar') .expect('got 404 error') - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); describe('.sendFile(path, options)', function () { it('should pass options to send module', function (done) { - request(createApp(path.resolve(fixtures, 'name.txt'), { start: 0, end: 1 })) - .get('/') - .expect(200, 'to', done) - }) + request( + createApp(path.resolve(fixtures, 'name.txt'), { start: 0, end: 1 }), + ) + .get('/') + .expect(200, 'to', done); + }); describe('with "acceptRanges" option', function () { describe('when true', function () { it('should advertise byte range accepted', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'nums.txt'), { - acceptRanges: true - }) - }) + acceptRanges: true, + }); + }); request(app) .get('/') .expect(200) .expect('Accept-Ranges', 'bytes') .expect('123456789') - .end(done) - }) + .end(done); + }); it('should respond to range request', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'nums.txt'), { - acceptRanges: true - }) - }) + acceptRanges: true, + }); + }); request(app) .get('/') .set('Range', 'bytes=0-4') - .expect(206, '12345', done) - }) - }) + .expect(206, '12345', done); + }); + }); describe('when false', function () { it('should not advertise accept-ranges', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'nums.txt'), { - acceptRanges: false - }) - }) + acceptRanges: false, + }); + }); request(app) .get('/') .expect(200) .expect(utils.shouldNotHaveHeader('Accept-Ranges')) - .end(done) - }) + .end(done); + }); it('should not honor range requests', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'nums.txt'), { - acceptRanges: false - }) - }) + acceptRanges: false, + }); + }); request(app) .get('/') .set('Range', 'bytes=0-4') - .expect(200, '123456789', done) - }) - }) - }) + .expect(200, '123456789', done); + }); + }); + }); describe('with "cacheControl" option', function () { describe('when true', function () { it('should send cache-control header', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - cacheControl: true - }) - }) + cacheControl: true, + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=0') - .end(done) - }) - }) + .end(done); + }); + }); describe('when false', function () { it('should not send cache-control header', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - cacheControl: false - }) - }) + cacheControl: false, + }); + }); request(app) .get('/') .expect(200) .expect(utils.shouldNotHaveHeader('Cache-Control')) - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); describe('with "dotfiles" option', function () { describe('when "allow"', function () { it('should allow dotfiles', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, '.name'), { - dotfiles: 'allow' - }) - }) + dotfiles: 'allow', + }); + }); request(app) .get('/') .expect(200) .expect(utils.shouldHaveBody(Buffer.from('tobi'))) - .end(done) - }) - }) + .end(done); + }); + }); describe('when "deny"', function () { it('should deny dotfiles', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, '.name'), { - dotfiles: 'deny' - }) - }) + dotfiles: 'deny', + }); + }); request(app) .get('/') .expect(403) .expect(/Forbidden/) - .end(done) - }) - }) + .end(done); + }); + }); describe('when "ignore"', function () { it('should ignore dotfiles', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, '.name'), { - dotfiles: 'ignore' - }) - }) + dotfiles: 'ignore', + }); + }); request(app) .get('/') .expect(404) .expect(/Not Found/) - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); describe('with "headers" option', function () { it('should set headers on response', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { headers: { 'X-Foo': 'Bar', - 'X-Bar': 'Foo' - } - }) - }) + 'X-Bar': 'Foo', + }, + }); + }); request(app) .get('/') .expect(200) .expect('X-Foo', 'Bar') .expect('X-Bar', 'Foo') - .end(done) - }) + .end(done); + }); it('should use last header when duplicated', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { headers: { 'X-Foo': 'Bar', - 'x-foo': 'bar' - } - }) - }) + 'x-foo': 'bar', + }, + }); + }); - request(app) - .get('/') - .expect(200) - .expect('X-Foo', 'bar') - .end(done) - }) + request(app).get('/').expect(200).expect('X-Foo', 'bar').end(done); + }); it('should override Content-Type', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { headers: { - 'Content-Type': 'text/x-custom' - } - }) - }) + 'Content-Type': 'text/x-custom', + }, + }); + }); request(app) .get('/') .expect(200) .expect('Content-Type', 'text/x-custom') - .end(done) - }) + .end(done); + }); it('should not set headers on 404', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'does-not-exist'), { headers: { - 'X-Foo': 'Bar' - } - }) - }) + 'X-Foo': 'Bar', + }, + }); + }); request(app) .get('/') .expect(404) .expect(utils.shouldNotHaveHeader('X-Foo')) - .end(done) - }) - }) + .end(done); + }); + }); describe('with "immutable" option', function () { describe('when true', function () { it('should send cache-control header with immutable', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - immutable: true - }) - }) + immutable: true, + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=0, immutable') - .end(done) - }) - }) + .end(done); + }); + }); describe('when false', function () { it('should not send cache-control header with immutable', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - immutable: false - }) - }) + immutable: false, + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=0') - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); describe('with "lastModified" option', function () { describe('when true', function () { it('should send last-modified header', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - lastModified: true - }) - }) + lastModified: true, + }); + }); request(app) .get('/') .expect(200) .expect(utils.shouldHaveHeader('Last-Modified')) - .end(done) - }) + .end(done); + }); it('should conditionally respond with if-modified-since', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - lastModified: true - }) - }) + lastModified: true, + }); + }); request(app) .get('/') - .set('If-Modified-Since', (new Date(Date.now() + 99999).toUTCString())) - .expect(304, done) - }) - }) + .set( + 'If-Modified-Since', + new Date(Date.now() + 99999).toUTCString(), + ) + .expect(304, done); + }); + }); describe('when false', function () { it('should not have last-modified header', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - lastModified: false - }) - }) + lastModified: false, + }); + }); request(app) .get('/') .expect(200) .expect(utils.shouldNotHaveHeader('Last-Modified')) - .end(done) - }) + .end(done); + }); it('should not honor if-modified-since', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - lastModified: false - }) - }) + lastModified: false, + }); + }); request(app) .get('/') - .set('If-Modified-Since', (new Date(Date.now() + 99999).toUTCString())) + .set( + 'If-Modified-Since', + new Date(Date.now() + 99999).toUTCString(), + ) .expect(200) .expect(utils.shouldNotHaveHeader('Last-Modified')) - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); describe('with "maxAge" option', function () { it('should set cache-control max-age to milliseconds', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - maxAge: 20000 - }) - }) + maxAge: 20000, + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=20') - .end(done) - }) + .end(done); + }); it('should cap cache-control max-age to 1 year', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - maxAge: 99999999999 - }) - }) + maxAge: 99999999999, + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=31536000') - .end(done) - }) + .end(done); + }); it('should min cache-control max-age to 0', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - maxAge: -20000 - }) - }) + maxAge: -20000, + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=0') - .end(done) - }) + .end(done); + }); it('should floor cache-control max-age', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - maxAge: 21911.23 - }) - }) + maxAge: 21911.23, + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=21') - .end(done) - }) + .end(done); + }); describe('when cacheControl: false', function () { it('should not send cache-control', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { cacheControl: false, - maxAge: 20000 - }) - }) + maxAge: 20000, + }); + }); request(app) .get('/') .expect(200) .expect(utils.shouldNotHaveHeader('Cache-Control')) - .end(done) - }) - }) + .end(done); + }); + }); describe('when string', function () { it('should accept plain number as milliseconds', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - maxAge: '20000' - }) - }) + maxAge: '20000', + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=20') - .end(done) - }) + .end(done); + }); it('should accept suffix "s" for seconds', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - maxAge: '20s' - }) - }) + maxAge: '20s', + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=20') - .end(done) - }) + .end(done); + }); it('should accept suffix "m" for minutes', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - maxAge: '20m' - }) - }) + maxAge: '20m', + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=1200') - .end(done) - }) + .end(done); + }); it('should accept suffix "d" for days', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile(path.resolve(fixtures, 'user.html'), { - maxAge: '20d' - }) - }) + maxAge: '20d', + }); + }); request(app) .get('/') .expect(200) .expect('Cache-Control', 'public, max-age=1728000') - .end(done) - }) - }) - }) + .end(done); + }); + }); + }); describe('with "root" option', function () { it('should allow relative path', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile('name.txt', { - root: fixtures - }) - }) + root: fixtures, + }); + }); - request(app) - .get('/') - .expect(200, 'tobi', done) - }) + request(app).get('/').expect(200, 'tobi', done); + }); it('should allow up within root', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile('fake/../name.txt', { - root: fixtures - }) - }) + root: fixtures, + }); + }); - request(app) - .get('/') - .expect(200, 'tobi', done) - }) + request(app).get('/').expect(200, 'tobi', done); + }); it('should reject up outside root', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.sendFile('..' + path.sep + path.relative(path.dirname(fixtures), path.join(fixtures, 'name.txt')), { - root: fixtures - }) - }) + res.sendFile( + '..' + + path.sep + + path.relative( + path.dirname(fixtures), + path.join(fixtures, 'name.txt'), + ), + { + root: fixtures, + }, + ); + }); - request(app) - .get('/') - .expect(403, done) - }) + request(app).get('/').expect(403, done); + }); it('should reject reading outside root', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { res.sendFile('../name.txt', { - root: fixtures - }) - }) + root: fixtures, + }); + }); - request(app) - .get('/') - .expect(403, done) - }) - }) - }) -}) + request(app).get('/').expect(403, done); + }); + }); + }); +}); function createApp(path, options, fn) { var app = express(); @@ -902,10 +886,10 @@ function createApp(path, options, fn) { return app; } -function tryRequire (name) { +function tryRequire(name) { try { - return require(name) + return require(name); } catch (e) { - return {} + return {}; } } diff --git a/test/res.sendStatus.js b/test/res.sendStatus.js index b244cf9d173..ed6828042b7 100644 --- a/test/res.sendStatus.js +++ b/test/res.sendStatus.js @@ -1,44 +1,40 @@ -'use strict' +'use strict'; -var express = require('..') -var request = require('supertest') +var express = require('..'); +var request = require('supertest'); describe('res', function () { describe('.sendStatus(statusCode)', function () { it('should send the status code and message as body', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.sendStatus(201); }); - request(app) - .get('/') - .expect(201, 'Created', done); - }) + request(app).get('/').expect(201, 'Created', done); + }); it('should work with unknown code', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.sendStatus(599); }); - request(app) - .get('/') - .expect(599, '599', done); - }) + request(app).get('/').expect(599, '599', done); + }); it('should raise error for invalid status code', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.sendStatus(undefined).end() - }) + res.sendStatus(undefined).end(); + }); request(app) .get('/') - .expect(500, /TypeError: Invalid status code/, done) - }) - }) -}) + .expect(500, /TypeError: Invalid status code/, done); + }); + }); +}); diff --git a/test/res.set.js b/test/res.set.js index 04511c1c95f..c32d54203a0 100644 --- a/test/res.set.js +++ b/test/res.set.js @@ -1,22 +1,22 @@ -'use strict' +'use strict'; var express = require('..'); var request = require('supertest'); -describe('res', function(){ - describe('.set(field, value)', function(){ - it('should set the response header field', function(done){ +describe('res', function () { + describe('.set(field, value)', function () { + it('should set the response header field', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.set('Content-Type', 'text/x-foo; charset=utf-8').end(); }); request(app) - .get('/') - .expect('Content-Type', 'text/x-foo; charset=utf-8') - .end(done); - }) + .get('/') + .expect('Content-Type', 'text/x-foo; charset=utf-8') + .end(done); + }); it('should coerce to a string', function (done) { var app = express(); @@ -27,25 +27,25 @@ describe('res', function(){ }); request(app) - .get('/') - .expect('X-Number', '123') - .expect(200, 'string', done); - }) - }) - - describe('.set(field, values)', function(){ - it('should set multiple response header fields', function(done){ + .get('/') + .expect('X-Number', '123') + .expect(200, 'string', done); + }); + }); + + describe('.set(field, values)', function () { + it('should set multiple response header fields', function (done) { var app = express(); - app.use(function(req, res){ - res.set('Set-Cookie', ["type=ninja", "language=javascript"]); + app.use(function (req, res) { + res.set('Set-Cookie', ['type=ninja', 'language=javascript']); res.send(res.get('Set-Cookie')); }); request(app) - .get('/') - .expect('["type=ninja","language=javascript"]', done); - }) + .get('/') + .expect('["type=ninja","language=javascript"]', done); + }); it('should coerce to an array of strings', function (done) { var app = express(); @@ -56,10 +56,10 @@ describe('res', function(){ }); request(app) - .get('/') - .expect('X-Numbers', '123, 456') - .expect(200, '["123","456"]', done); - }) + .get('/') + .expect('X-Numbers', '123, 456') + .expect(200, '["123","456"]', done); + }); it('should not set a charset of one is already set', function (done) { var app = express(); @@ -70,42 +70,44 @@ describe('res', function(){ }); request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=lol') - .expect(200, done); - }) + .get('/') + .expect('Content-Type', 'text/html; charset=lol') + .expect(200, done); + }); it('should throw when Content-Type is an array', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.set('Content-Type', ['text/html']) - res.end() + res.set('Content-Type', ['text/html']); + res.end(); }); request(app) - .get('/') - .expect(500, /TypeError: Content-Type cannot be set to an Array/, done) - }) - }) + .get('/') + .expect(500, /TypeError: Content-Type cannot be set to an Array/, done); + }); + }); - describe('.set(object)', function(){ - it('should set multiple fields', function(done){ + describe('.set(object)', function () { + it('should set multiple fields', function (done) { var app = express(); - app.use(function(req, res){ - res.set({ - 'X-Foo': 'bar', - 'X-Bar': 'baz' - }).end(); + app.use(function (req, res) { + res + .set({ + 'X-Foo': 'bar', + 'X-Bar': 'baz', + }) + .end(); }); request(app) - .get('/') - .expect('X-Foo', 'bar') - .expect('X-Bar', 'baz') - .end(done); - }) + .get('/') + .expect('X-Foo', 'bar') + .expect('X-Bar', 'baz') + .end(done); + }); it('should coerce to a string', function (done) { var app = express(); @@ -116,9 +118,9 @@ describe('res', function(){ }); request(app) - .get('/') - .expect('X-Number', '123') - .expect(200, 'string', done); - }) - }) -}) + .get('/') + .expect('X-Number', '123') + .expect(200, 'string', done); + }); + }); +}); diff --git a/test/res.status.js b/test/res.status.js index 59c8a57e702..29845ee27df 100644 --- a/test/res.status.js +++ b/test/res.status.js @@ -1,10 +1,9 @@ -'use strict' +'use strict'; const express = require('../.'); const request = require('supertest'); describe('res', function () { describe('.status(code)', function () { - it('should set the status code when valid', function (done) { var app = express(); @@ -12,109 +11,91 @@ describe('res', function () { res.status(200).end(); }); - request(app) - .get('/') - .expect(200, done); + request(app).get('/').expect(200, done); }); - describe('accept valid ranges', function() { + describe('accept valid ranges', function () { // not testing w/ 100, because that has specific meaning and behavior in Node as Expect: 100-continue it('should set the response status code to 101', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.status(101).end() - }) + res.status(101).end(); + }); - request(app) - .get('/') - .expect(101, done) - }) + request(app).get('/').expect(101, done); + }); it('should set the response status code to 201', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.status(201).end() - }) + res.status(201).end(); + }); - request(app) - .get('/') - .expect(201, done) - }) + request(app).get('/').expect(201, done); + }); it('should set the response status code to 302', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.status(302).end() - }) + res.status(302).end(); + }); - request(app) - .get('/') - .expect(302, done) - }) + request(app).get('/').expect(302, done); + }); it('should set the response status code to 403', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.status(403).end() - }) + res.status(403).end(); + }); - request(app) - .get('/') - .expect(403, done) - }) + request(app).get('/').expect(403, done); + }); it('should set the response status code to 501', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.status(501).end() - }) + res.status(501).end(); + }); - request(app) - .get('/') - .expect(501, done) - }) + request(app).get('/').expect(501, done); + }); it('should set the response status code to 700', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.status(700).end() - }) + res.status(700).end(); + }); - request(app) - .get('/') - .expect(700, done) - }) + request(app).get('/').expect(700, done); + }); it('should set the response status code to 800', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.status(800).end() - }) + res.status(800).end(); + }); - request(app) - .get('/') - .expect(800, done) - }) + request(app).get('/').expect(800, done); + }); it('should set the response status code to 900', function (done) { - var app = express() + var app = express(); app.use(function (req, res) { - res.status(900).end() - }) + res.status(900).end(); + }); - request(app) - .get('/') - .expect(900, done) - }) - }) + request(app).get('/').expect(900, done); + }); + }); describe('invalid status codes', function () { it('should raise error for status code below 100', function (done) { @@ -181,7 +162,7 @@ describe('res', function () { var app = express(); app.use(function (req, res) { - res.status("200").end(); + res.status('200').end(); }); request(app) @@ -203,4 +184,3 @@ describe('res', function () { }); }); }); - diff --git a/test/res.type.js b/test/res.type.js index 09285af3914..d0654f3c93e 100644 --- a/test/res.type.js +++ b/test/res.type.js @@ -1,46 +1,45 @@ -'use strict' +'use strict'; -var express = require('../') - , request = require('supertest'); +var express = require('../'), + request = require('supertest'); -describe('res', function(){ - describe('.type(str)', function(){ - it('should set the Content-Type based on a filename', function(done){ +describe('res', function () { + describe('.type(str)', function () { + it('should set the Content-Type based on a filename', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.type('foo.js').end('var name = "tj";'); }); request(app) - .get('/') - .expect('Content-Type', 'text/javascript; charset=utf-8') - .end(done) - }) + .get('/') + .expect('Content-Type', 'text/javascript; charset=utf-8') + .end(done); + }); - it('should default to application/octet-stream', function(done){ + it('should default to application/octet-stream', function (done) { var app = express(); - app.use(function(req, res){ + app.use(function (req, res) { res.type('rawr').end('var name = "tj";'); }); request(app) - .get('/') - .expect('Content-Type', 'application/octet-stream', done); - }) + .get('/') + .expect('Content-Type', 'application/octet-stream', done); + }); - it('should set the Content-Type with type/subtype', function(done){ + it('should set the Content-Type with type/subtype', function (done) { var app = express(); - app.use(function(req, res){ - res.type('application/vnd.amazon.ebook') - .end('var name = "tj";'); + app.use(function (req, res) { + res.type('application/vnd.amazon.ebook').end('var name = "tj";'); }); request(app) - .get('/') - .expect('Content-Type', 'application/vnd.amazon.ebook', done); - }) - }) -}) + .get('/') + .expect('Content-Type', 'application/vnd.amazon.ebook', done); + }); + }); +}); diff --git a/test/res.vary.js b/test/res.vary.js index ff3c9716529..0548c6c3118 100644 --- a/test/res.vary.js +++ b/test/res.vary.js @@ -1,11 +1,11 @@ -'use strict' +'use strict'; var express = require('..'); var request = require('supertest'); var utils = require('./support/utils'); -describe('res.vary()', function(){ - describe('with no arguments', function(){ +describe('res.vary()', function () { + describe('with no arguments', function () { it('should throw error', function (done) { var app = express(); @@ -15,12 +15,12 @@ describe('res.vary()', function(){ }); request(app) - .get('/') - .expect(500, /field.*required/, done) - }) - }) + .get('/') + .expect(500, /field.*required/, done); + }); + }); - describe('with an empty array', function(){ + describe('with an empty array', function () { it('should not set Vary', function (done) { var app = express(); @@ -30,13 +30,13 @@ describe('res.vary()', function(){ }); request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('Vary')) - .expect(200, done); - }) - }) + .get('/') + .expect(utils.shouldNotHaveHeader('Vary')) + .expect(200, done); + }); + }); - describe('with an array', function(){ + describe('with an array', function () { it('should set the values', function (done) { var app = express(); @@ -46,13 +46,13 @@ describe('res.vary()', function(){ }); request(app) - .get('/') - .expect('Vary', 'Accept, Accept-Language, Accept-Encoding') - .expect(200, done); - }) - }) + .get('/') + .expect('Vary', 'Accept, Accept-Language, Accept-Encoding') + .expect(200, done); + }); + }); - describe('with a string', function(){ + describe('with a string', function () { it('should set the value', function (done) { var app = express(); @@ -61,14 +61,11 @@ describe('res.vary()', function(){ res.end(); }); - request(app) - .get('/') - .expect('Vary', 'Accept') - .expect(200, done); - }) - }) + request(app).get('/').expect('Vary', 'Accept').expect(200, done); + }); + }); - describe('when the value is present', function(){ + describe('when the value is present', function () { it('should not add it again', function (done) { var app = express(); @@ -82,9 +79,9 @@ describe('res.vary()', function(){ }); request(app) - .get('/') - .expect('Vary', 'Accept, Accept-Encoding') - .expect(200, done); - }) - }) -}) + .get('/') + .expect('Vary', 'Accept, Accept-Encoding') + .expect(200, done); + }); + }); +}); diff --git a/test/support/env.js b/test/support/env.js index 000638ceeae..0c4248023cd 100644 --- a/test/support/env.js +++ b/test/support/env.js @@ -1,3 +1,2 @@ - process.env.NODE_ENV = 'test'; process.env.NO_DEPRECATION = 'body-parser,express'; diff --git a/test/support/tmpl.js b/test/support/tmpl.js index bab65669d33..4aa0a132ca0 100644 --- a/test/support/tmpl.js +++ b/test/support/tmpl.js @@ -13,7 +13,7 @@ module.exports = function renderFile(fileName, options, callback) { str = str.replace(variableRegExp, generateVariableLookup(options)); } catch (e) { err = e; - err.name = 'RenderError' + err.name = 'RenderError'; } callback(err, str); diff --git a/test/support/utils.js b/test/support/utils.js index 5ad4ca98410..1641ca23c41 100644 --- a/test/support/utils.js +++ b/test/support/utils.js @@ -1,22 +1,21 @@ - /** * Module dependencies. * @private */ var assert = require('assert'); -var Buffer = require('safe-buffer').Buffer +var Buffer = require('safe-buffer').Buffer; /** * Module exports. * @public */ -exports.shouldHaveBody = shouldHaveBody -exports.shouldHaveHeader = shouldHaveHeader -exports.shouldNotHaveBody = shouldNotHaveBody +exports.shouldHaveBody = shouldHaveBody; +exports.shouldHaveHeader = shouldHaveHeader; +exports.shouldNotHaveBody = shouldNotHaveBody; exports.shouldNotHaveHeader = shouldNotHaveHeader; -exports.shouldSkipQuery = shouldSkipQuery +exports.shouldSkipQuery = shouldSkipQuery; /** * Assert that a supertest response has a specific body. @@ -25,14 +24,12 @@ exports.shouldSkipQuery = shouldSkipQuery * @returns {function} */ -function shouldHaveBody (buf) { +function shouldHaveBody(buf) { return function (res) { - var body = !Buffer.isBuffer(res.body) - ? Buffer.from(res.text) - : res.body - assert.ok(body, 'response has body') - assert.strictEqual(body.toString('hex'), buf.toString('hex')) - } + var body = !Buffer.isBuffer(res.body) ? Buffer.from(res.text) : res.body; + assert.ok(body, 'response has body'); + assert.strictEqual(body.toString('hex'), buf.toString('hex')); + }; } /** @@ -42,10 +39,13 @@ function shouldHaveBody (buf) { * @returns {function} */ -function shouldHaveHeader (header) { +function shouldHaveHeader(header) { return function (res) { - assert.ok((header.toLowerCase() in res.headers), 'should have header ' + header) - } + assert.ok( + header.toLowerCase() in res.headers, + 'should have header ' + header, + ); + }; } /** @@ -54,10 +54,10 @@ function shouldHaveHeader (header) { * @returns {function} */ -function shouldNotHaveBody () { +function shouldNotHaveBody() { return function (res) { - assert.ok(res.text === '' || res.text === undefined) - } + assert.ok(res.text === '' || res.text === undefined); + }; } /** @@ -68,7 +68,10 @@ function shouldNotHaveBody () { */ function shouldNotHaveHeader(header) { return function (res) { - assert.ok(!(header.toLowerCase() in res.headers), 'should not have header ' + header); + assert.ok( + !(header.toLowerCase() in res.headers), + 'should not have header ' + header, + ); }; } @@ -81,6 +84,5 @@ function shouldSkipQuery(versionString) { // update this implementation to run on supported versions of 21 once they exist // upstream tracking https://github.com/nodejs/node/issues/51562 // express tracking issue: https://github.com/expressjs/express/issues/5615 - return Number(getMajorVersion(versionString)) === 21 + return Number(getMajorVersion(versionString)) === 21; } - diff --git a/test/utils.js b/test/utils.js index aff3f03aa33..f233a2537e1 100644 --- a/test/utils.js +++ b/test/utils.js @@ -1,30 +1,35 @@ -'use strict' +'use strict'; var assert = require('assert'); -var Buffer = require('safe-buffer').Buffer +var Buffer = require('safe-buffer').Buffer; var utils = require('../lib/utils'); -describe('utils.etag(body, encoding)', function(){ - it('should support strings', function(){ - assert.strictEqual(utils.etag('express!'), - '"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"') - }) +describe('utils.etag(body, encoding)', function () { + it('should support strings', function () { + assert.strictEqual( + utils.etag('express!'), + '"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"', + ); + }); - it('should support utf8 strings', function(){ - assert.strictEqual(utils.etag('express❤', 'utf8'), - '"a-JBiXf7GyzxwcrxY4hVXUwa7tmks"') - }) + it('should support utf8 strings', function () { + assert.strictEqual( + utils.etag('express❤', 'utf8'), + '"a-JBiXf7GyzxwcrxY4hVXUwa7tmks"', + ); + }); - it('should support buffer', function(){ - assert.strictEqual(utils.etag(Buffer.from('express!')), - '"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"') - }) + it('should support buffer', function () { + assert.strictEqual( + utils.etag(Buffer.from('express!')), + '"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"', + ); + }); - it('should support empty string', function(){ - assert.strictEqual(utils.etag(''), - '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"') - }) -}) + it('should support empty string', function () { + assert.strictEqual(utils.etag(''), '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'); + }); +}); describe('utils.setCharset(type, charset)', function () { it('should do anything without type', function () { @@ -36,36 +41,50 @@ describe('utils.setCharset(type, charset)', function () { }); it('should keep charset if not given charset', function () { - assert.strictEqual(utils.setCharset('text/html; charset=utf-8'), 'text/html; charset=utf-8'); + assert.strictEqual( + utils.setCharset('text/html; charset=utf-8'), + 'text/html; charset=utf-8', + ); }); it('should set charset', function () { - assert.strictEqual(utils.setCharset('text/html', 'utf-8'), 'text/html; charset=utf-8'); + assert.strictEqual( + utils.setCharset('text/html', 'utf-8'), + 'text/html; charset=utf-8', + ); }); it('should override charset', function () { - assert.strictEqual(utils.setCharset('text/html; charset=iso-8859-1', 'utf-8'), 'text/html; charset=utf-8'); + assert.strictEqual( + utils.setCharset('text/html; charset=iso-8859-1', 'utf-8'), + 'text/html; charset=utf-8', + ); }); }); -describe('utils.wetag(body, encoding)', function(){ - it('should support strings', function(){ - assert.strictEqual(utils.wetag('express!'), - 'W/"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"') - }) +describe('utils.wetag(body, encoding)', function () { + it('should support strings', function () { + assert.strictEqual( + utils.wetag('express!'), + 'W/"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"', + ); + }); - it('should support utf8 strings', function(){ - assert.strictEqual(utils.wetag('express❤', 'utf8'), - 'W/"a-JBiXf7GyzxwcrxY4hVXUwa7tmks"') - }) + it('should support utf8 strings', function () { + assert.strictEqual( + utils.wetag('express❤', 'utf8'), + 'W/"a-JBiXf7GyzxwcrxY4hVXUwa7tmks"', + ); + }); - it('should support buffer', function(){ - assert.strictEqual(utils.wetag(Buffer.from('express!')), - 'W/"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"') - }) + it('should support buffer', function () { + assert.strictEqual( + utils.wetag(Buffer.from('express!')), + 'W/"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"', + ); + }); - it('should support empty string', function(){ - assert.strictEqual(utils.wetag(''), - 'W/"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"') - }) -}) + it('should support empty string', function () { + assert.strictEqual(utils.wetag(''), 'W/"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'); + }); +}); From 9d16f41bd9cfedd14b3f24cceab4f5c589175350 Mon Sep 17 00:00:00 2001 From: AbdelMonaam Aouini <52112750+Abdel-Monaam-Aouini@users.noreply.github.com> Date: Sun, 3 Nov 2024 08:42:12 +0100 Subject: [PATCH 2/2] Update package.json MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ulises Gascón --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index ead22cf29cd..490923f599f 100644 --- a/package.json +++ b/package.json @@ -93,7 +93,8 @@ "lib/" ], "scripts": { - "format": "prettier --write \"**/*.js\"", + "format": "prettier \"**/*.js\"", + "format:fix": "prettier --write \"**/*.js\"", "lint": "eslint .", "test": "mocha --require test/support/env --reporter spec --check-leaks test/ test/acceptance/", "test-ci": "nyc --exclude examples --exclude test --exclude benchmarks --reporter=lcovonly --reporter=text npm test",