Skip to content

Commit

Permalink
feat: add respondWithRequestBody option for POST endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
anoack93 committed May 27, 2021
1 parent a3246d6 commit 0dc4a39
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
8 changes: 8 additions & 0 deletions examples/mock-api/v2/book.post.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"requestOptions": {},
"responseOptions": {
"delay_ms": 100,
"statusCode": 201,
"respondWithRequestBody": true
}
}
6 changes: 5 additions & 1 deletion src/serve-mocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ function serveMocks (mockDirectory, port, hostname) {
const requestValidation = requestOptions.validation ? requestOptions.validation : {}
const responseDelay = responseOptions.delay_ms ? responseOptions.delay_ms : 2000
const statusCode = responseOptions.statusCode ? responseOptions.statusCode : 200
const response = endpointParams.response ? endpointParams.response : { success: true }
let response = endpointParams.response ? endpointParams.response : { success: true }
console.log(`receiving POST request on ${apiPath} with body:`, req.body)

setTimeout(() => {
Expand All @@ -128,6 +128,10 @@ function serveMocks (mockDirectory, port, hostname) {
}
}

if (responseOptions.respondWithRequestBody === true) {
response = req.body
}

res.status(statusCode).send(response)
}, responseDelay)
})
Expand Down
18 changes: 17 additions & 1 deletion src/serve-mocks.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ describe('serve-mocks', () => {
expect(response.body).toEqual(expectedResponse)
})

it('should respond with request body if option is set', async () => {
expect.assertions(3) // number of expect calls in this test

const randomId = Math.floor(Math.random() * 100)
const requestBody = {
id: randomId,
author: 'Lorem Ipsum'
}

const response = await request.post('/v2/book').send(requestBody)

expect(response.status).toBe(201)
expect(response.headers['content-type']).toBe('application/json; charset=utf-8')
expect(response.body).toEqual(requestBody)
})

it('should respond with 422 unprocessable entity when posting invalid user', async () => {
expect.assertions(1) // number of expect calls in this test

Expand Down Expand Up @@ -109,4 +125,4 @@ describe('serve-mocks', () => {
expect(response.status).toBe(200)
expect(response.headers['content-type']).toBe('image/png')
})
})
})

0 comments on commit 0dc4a39

Please sign in to comment.