You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
3.0 KiB
JavaScript

var expect = require('expect')
var Router = require('../lib/router')
describe('Router', function () {
it('→ exists', function () {
expect(Router).toExist()
})
it('→ add root node', function (done) {
var router = new Router()
router.add('/', function () { return 'some value' })
router.route('/', function (err, handlerResult) {
expect(err).toBe(null)
expect(handlerResult).toBe('some value')
done()
})
})
it('→ add/get nested route', function (done) {
var router = new Router()
router.add('/some/path/here', function () { return 'some value' })
router.route('/some/path/here', function (err, handlerResult) {
expect(err).toBe(null)
expect(handlerResult).toBe('some value')
done()
})
})
it('→ get error in callback for missing handler', function (done) {
var router = new Router()
router.route('/some/fake/path', function (err, handlerResult) {
expect(err).toBeA(Error)
expect(err.message).toMatch(/not found/)
expect(handlerResult).toNotExist()
done()
})
})
it('→ get routes based on regex', function (done) {
var router = new Router()
router.add(['/by/id', /\d+/], function (someId) {
expect(someId).toBe('123')
})
router.route('/by/id/123', function (err) {
expect(err).toBe(null, err && err.message)
done()
})
})
it('→ get based on regex with multiple captures global', function (done) {
var router = new Router()
router.add(['by', 'order', /(\d+)/g], function (one, two, three) {
expect(one).toBe('1')
expect(two).toBe('2')
expect(three).toBe('3')
})
router.route('/by/order/1-2-3', function (err) {
expect(err).toBe(null, err && err.message)
done()
})
})
it('→ get based regex with multiple captures not global', function (done) {
var router = new Router()
router.add(['by', 'order', /(\d+)/], function (one, two, three) {
expect(one).toBe('1')
expect(two).toNotExist()
expect(three).toNotExist()
})
router.route('/by/order/1-2-3', function (err) {
expect(err).toBe(null, err && err.message)
done()
})
})
it('→ get based on function', function (done) {
function toInt(part) {
var results = /^(\d+)$/.exec(part)
if (results) {
return parseInt(results[0], 10)
} else {
return null
}
}
var router = new Router()
router.add(['by', 'order', toInt], function (val) {
expect(val).toBe(123)
})
router.route('/by/order/123', function (err) {
expect(err).toBe(null, err && err.message)
done()
})
})
it('→ check not found error', function (done) {
var router = new Router()
router.route('/not/real/id', function (err) {
expect(Router.isNotFound(err)).toBe(true)
done()
})
})
it('→ check not found error on not real error', function () {
expect(Router.isNotFound(new Error('Not the missing error'))).toBe(false)
})
})