Skip to content

Commit

Permalink
make tests for custom token() usage
Browse files Browse the repository at this point in the history
  • Loading branch information
bmeck committed Oct 11, 2016
1 parent 1533cdc commit 6536b90
Showing 1 changed file with 97 additions and 0 deletions.
97 changes: 97 additions & 0 deletions test/morgan.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ var join = require('path').join
var morgan = require('..')
var request = require('supertest')
var split = require('split')
var url = require('url')

describe('morgan()', function () {
describe('arguments', function () {
Expand Down Expand Up @@ -1316,6 +1317,102 @@ describe('morgan.compile(format)', function () {
})
})

describe('morgan.token(name, function)', function () {
it('should overwrite existing functions if called multiple times', function (done) {
function token (req, res, arg) {
return arg && url.parse(req.url)[arg]
}
var urlToken = morgan.url
morgan.token('url', token)
assert.equal(morgan.url, token)
morgan.token('url', urlToken)
done()
})

describe('should use the string `-` if return value of the token function is falsey', function () {
function test (v, done) {
morgan.token('ret', function ret (req, res, arg) {
return arg
})
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.equal(line, '-')
done()
})

var stream = createLineStream(function (line) {
cb(null, null, line)
})

var server = createServer(':ret', { stream: stream }, function (req, res, next) {
next()
})

request(server)
.get('/')
.expect(200, cb)
}
[
0,
NaN,
false,
'',
null,
undefined
].forEach(function (v) {
it('for ' + (String(v) || JSON.stringify(v)), function (done) {
test(v, done)
})
})
})

it('should not see empty brackets as an argument value', function (done) {
morgan.token('checkempty', function ret (req, res, arg) {
assert.equal(arg, undefined)
assert.equal(arguments.length, 2)
cb(null)
})
var cb = after(3, function (err, res, line) {
if (err) return done(err)
assert.equal(line, '-[]')
done()
})

var stream = createLineStream(function (line) {
cb(null, null, line)
})

var server = createServer(':checkempty[]', { stream: stream }, function (req, res, next) {
next()
})

request(server)
.get('/')
.expect(200, cb)
})

it('should use the result', function (done) {
morgan.token('urlpart', function ret (req, res, arg) {
return url.parse(req.url)[arg]
})
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.equal(line, 'foo=bar')
done()
})

var stream = createLineStream(function (line) {
cb(null, null, line)
})

var server = createServer(':urlpart[query]', { stream: stream }, function (req, res, next) {
next()
})

request(server).post('/test').query('foo=bar').expect(200, cb)
})
})

function after (count, callback) {
var args = new Array(3)
var i = 0
Expand Down

0 comments on commit 6536b90

Please sign in to comment.