Browse Source

add async mock capability.. fixes #26

master
Lloyd Brookes 9 years ago
parent
commit
5350186614
  1. 8
      example/mock-async/.local-web-server.json
  2. 10
      example/mock-async/mocks/delayed.js
  3. 3
      lib/middleware.js
  4. 28
      test/test.js

8
example/mock-async/.local-web-server.json

@ -0,0 +1,8 @@
{
"mocks": [
{
"route": "/",
"module": "/mocks/delayed.js"
}
]
}

10
example/mock-async/mocks/delayed.js

@ -0,0 +1,10 @@
module.exports = {
response: function (ctx) {
return new Promise((resolve, reject) => {
setTimeout(() => {
ctx.body = `<h1>You waited 2s for this</h1>`
resolve()
}, 2000)
})
}
}

3
lib/middleware.js

@ -101,10 +101,9 @@ function mockResponses (route, targets) {
} }
if (target) { if (target) {
// debug('target response: %s', target.response)
if (t.isFunction(target.response)) { if (t.isFunction(target.response)) {
const pathMatches = ctx.path.match(pathRe).slice(1) const pathMatches = ctx.path.match(pathRe).slice(1)
target.response.apply(null, [ctx].concat(pathMatches))
return target.response.apply(null, [ctx].concat(pathMatches))
} else if (t.isPlainObject(target.response)) { } else if (t.isPlainObject(target.response)) {
Object.assign(ctx.response, target.response) Object.assign(ctx.response, target.response)
} else { } else {

28
test/test.js

@ -335,3 +335,31 @@ test('mock: response function args', function (t) {
.then(server.close.bind(server)) .then(server.close.bind(server))
}) })
}) })
test('mock: async response function', function (t) {
t.plan(2)
const app = localWebServer({
log: { format: 'none' },
mocks: [
{
route: '/test',
responses: {
response: function (ctx) {
return new Promise((resolve, reject) => {
setTimeout(() => {
ctx.body = 'test'
resolve()
}, 10)
})
}
}
}
]
})
const server = http.createServer(app.callback())
server.listen(8100, () => {
request('http://localhost:8100/test')
.then(checkResponse(t, 200, /test/))
.then(server.close.bind(server))
})
})
Loading…
Cancel
Save