routeGen.test.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import routeGen from './routeGen'
  2. import { model, agency } from './_samples'
  3. import mongoose from 'mongoose'
  4. class Model {
  5. constructor () {
  6. this.modelName = 'Gisele'
  7. }
  8. static find (criteria, options, callback) {
  9. let { skip, limit } = options
  10. const myModel = model.slice(skip, skip + limit)
  11. if (myModel) {
  12. callback(undefined, myModel)
  13. } else {
  14. callback(Error('model not found'), undefined)
  15. }
  16. }
  17. static findOne (criteria, callback) {
  18. let { _id } = criteria
  19. const myModel = model.find((m) => {
  20. return (mongoose.Types.ObjectId(m._id) === _id)
  21. })
  22. if (myModel) {
  23. callback(undefined, myModel)
  24. } else {
  25. callback(Error('model not found'), undefined)
  26. }
  27. }
  28. save () {
  29. throw Error('save not implemented.')
  30. }
  31. remove () {
  32. throw Error('remove not implemented.')
  33. }
  34. }
  35. class Result {
  36. constructor () {
  37. this._body = null
  38. this._status = null
  39. }
  40. status (value) {
  41. this._status = value
  42. }
  43. send (data) {
  44. this._body = data
  45. }
  46. json (data) {
  47. this._status = 200
  48. this._body = data
  49. }
  50. }
  51. describe('routeGen for versioned models', () => {
  52. const route = routeGen(Model)
  53. const res = new Result()
  54. it('generates the handlers', () => {
  55. // Generate a version controlled model
  56. expect(route.get).not.toBeUndefined()
  57. expect(route.post).not.toBeUndefined()
  58. expect(route.put).not.toBeUndefined()
  59. expect(route.del).not.toBeUndefined()
  60. })
  61. it('get without arguments calls Model.find with the right parameters', () => {
  62. // call the GET handler
  63. const reqList = { params: {}, query: { limit: 2, offset: 1 } }
  64. route.get(reqList, res)
  65. expect(res._body).toEqual(model.slice(1, 3))
  66. expect(res._status).toBe(200)
  67. })
  68. it('return empty lists.', () => {
  69. // call the GET handler
  70. const reqList = { params: {}, query: { limit: 1, offset: 100 } }
  71. route.get(reqList, res)
  72. expect(res._body).toEqual([])
  73. expect(res._status).toBe(200)
  74. })
  75. it('get with arguments calls Model.findOne with the right parameters', () => {
  76. const reqElem = { params: { id: '58d3d6883d34293254afae42' }, query: {} }
  77. route.get(reqElem, res)
  78. expect(res._body).toEqual(model[0])
  79. expect(res._status).toBe(200)
  80. })
  81. it('return error when item is not found', () => {
  82. const reqElem = { params: { id: '58d3d6883d34343254afae42' }, query: {} }
  83. route.get(reqElem, res)
  84. expect(res._body).toEqual(model[0])
  85. expect(res._status).toBe(200)
  86. })
  87. })