add async mock capability.. fixes #26
This commit is contained in:
8
example/mock-async/.local-web-server.json
Normal file
8
example/mock-async/.local-web-server.json
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"mocks": [
|
||||||
|
{
|
||||||
|
"route": "/",
|
||||||
|
"module": "/mocks/delayed.js"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
10
example/mock-async/mocks/delayed.js
Normal file
10
example/mock-async/mocks/delayed.js
Normal file
@ -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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
@ -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
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))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
Reference in New Issue
Block a user