Browse Source

mock responses

master
Lloyd Brookes 9 years ago
parent
commit
f96c9382cb
  1. 7
      example/mock/mocks/trees.json
  2. 26
      example/mock/mocks/trees.mock.js
  3. 18
      lib/middleware.js

7
example/mock/mocks/trees.json

@ -0,0 +1,7 @@
[
{ "id": 1, "name": "Conifer", "maxHeight": 115 },
{ "id": 2, "name": "Eucalyptus", "maxHeight": 210 },
{ "id": 3, "name": "Ash", "maxHeight": 40 },
{ "id": 4, "name": "Elder", "maxHeight": 5 },
{ "id": 5, "name": "Holly", "maxHeight": 10 }
]

26
example/mock/mocks/trees.mock.js

@ -1,28 +1,21 @@
const data = [
{ id: 1, name: 'Conifer', maxHeight: 115 },
{ id: 2, name: 'Eucalyptus', maxHeight: 210 },
{ id: 3, name: 'Ash', maxHeight: 40 },
{ id: 4, name: 'Elder', maxHeight: 5 },
{ id: 5, name: 'Holly', maxHeight: 10 }
]
const data = require('./trees')
module.exports = [
/* CREATE */
{
request: { method: 'POST' },
response: {
status: 201,
location: '/tree/1'
response: function (ctx) {
data.push(ctx.request.body)
this.status = 201
this.location = '/tree/1'
}
},
/* READ */
{
request: { method: 'GET' },
response: {
status: 200,
body: function (ctx) {
return data.filter(tree => tree.maxHeight > Number(ctx.query.tallerThan))
}
response: function (ctx) {
this.status = 200
this.body = data.filter(tree => tree.maxHeight > Number(ctx.query.tallerThan || 0))
}
},
/* UPDATE (forbidden on collection)*/
@ -36,3 +29,6 @@ module.exports = [
response: { status: 404 }
}
]
// curl -i http://localhost:8000/trees -H 'content-type: application/json' -d '{"id":6, "name":"Oak", "maxHeight": 100 }'
// curl -i http://localhost:8000/trees

18
lib/middleware.js

@ -86,20 +86,12 @@ function mockResponses (options) {
mock = mocks.find(mock => !mock.request)
}
const mockedReponse = {}
/* resolve any functions on the mock */
Object.keys(mock.response).forEach(key => {
if (t.isFunction(mock.response[key])) {
mockedReponse[key] = mock.response[key](ctx)
} else {
mockedReponse[key] = mock.response[key]
}
})
if (mock) {
Object.assign(ctx.response, mockedReponse)
// debug('mocked response', JSON.stringify(mockedReponse))
// debug('actual response', JSON.stringify(ctx.response))
let mockedResponse = mock.response
if (t.isFunction(mock.response)) {
mockedResponse = new mock.response(ctx)
}
Object.assign(ctx.response, mockedResponse)
}
} else {
return next()

Loading…
Cancel
Save