jxson
10/18/2012 - 11:23 PM

HAL Chai plugin

HAL Chai plugin

var request = require('supertest')
  , chai = require('chai')
  , hal = require('../hal')
  , assert = chai.assert
  , server = require('../server')

chai.use(hal)

describe('description resource', function(){
  it('should be return a valid hal doc', function(done){
    request(server)
    .get('/')
    .set('accept', 'application/json+hal')
    .expect('content-type', 'application/json+hal')
    .expect('content-length', /\d$/g)
    .expect('etag', /(.*)/)
    .expect(200)
    .end(function(err, res){
      if (err) return done(err)

      assert.hal(res.body)
      assert.links(res.body, 'users') // has _links.users

      done()
    })
  })
})
// http://chaijs.com/guide/plugins/
module.exports = function(chai, utils){
  var Assertion = chai.Assertion
    , assert = chai.assert

  Assertion.addProperty('resource', function(){
    var doc = this._obj
      , message = utils.flag(this, 'message')

    new Assertion(doc, message).to.be.an('object')
    new Assertion(doc, message).to.link('self')
  })

  Assertion.addMethod('link', function(rel){
    var doc = this._obj
      , message = utils.flag(this, 'message')
      , _path = '_links.' + rel
      , href = _path + '.href'


    new Assertion(doc, message).to.be.an('object')
    new Assertion(doc, message).to.have.property('_links')
    new Assertion(doc, message).to.have.deep.property(_path)
    new Assertion(doc, message).to.have.deep.property(href)
  })

  assert.hal = function(doc, message){
    var message = message || 'HAL document'

    new Assertion(doc, message).to.be.a.resource
  }

  assert.linked = function(doc, rel, message){
    var message = message || 'HAL document link'

    new Assertion(doc, message).to.link(rel)
  }
}