serverless-express
serverless-express copied to clipboard
How to test handler code
First of all thank you so much for your great work and effort in maintaining this library. I'm very happy you have added an integration and unit test to the repository.
How can I test our handler code?
Our handler looks this:
//handler.js
import serverlessExpress from '@vendia/serverless-express'
import app from './app'
export default serverlessExpress({app}).handler
using express
//app.js
...
app.get('/health', (req, res, next) => {
response.setHeader('isBase64Encoded', true)
response.header('content-type', 'application/json')
res.status(200).send({
healthy: true,
status:200,
})
})
I would like to have a jest test handler.test.js in our code repo. This is a smoke test to see if things are more or less okay. The handler might still not run on AWS but at least we'll catch more gross errors in Jest on dev machine rather than waiting for the code to be pushed to staging to do an E2E test with Cypress.
I've tried passing an event but at best I'm getting an empty object response {}
//handler.test.js
import handler from '../handler'
describe('handler.js', () => {
it('GET /takeaway/health should return 200', async () => {
const event = {
headers: {},
httpMethod: 'GET',
path: '/health',
requestContext: {
stage: 'prod',
},
}
const context = {}
const response = handler(event, context)
console.log('response', JSON.stringify(response, null, 2))
expect(response.statusCode).toEqual(200)
const body = JSON.parse(atob(response.body))
// console.log('body', JSON.stringify(body, null, 2))
expect(body.status).toEqual(200)
expect(body.healthy).toEqual(true)
})
})
I found now a closed Issue https://github.com/vendia/serverless-express/issues/363. I've tried copy pasting the whole structure of https://github.com/vendia/serverless-express/blob/mainline/jest-helpers/api-gateway-v1-event.js but got a response with an empty object {}. I'm going to try https://github.com/serverless/event-mocks
Hmm... You probably need const response = await handler(event, context)
Thank you @brettstack . Adding await fixed the problem. I had started with the await and then removed it when using the wrong event and I didn't put it back.
In the end it was enough to just use this event:
headers: {},
httpMethod: 'GET',
path: '/takeaway/health',
requestContext: {
stage: 'prod',
},
}```
How can I disable the console.debug logging to avoid polluting the jest tests?
The latest version should only log when process.env.NODE_ENV === 'development'
.
Thanks! Yes indeed launching NODE_ENV=testing jest handler
hides the debug logs.
@brettstack would you be interested in a PR to add a section How to unit test to the Readme.md?
That'd be great!
One thing that could be helpful would be actually publishing the jest-helpers
in the package (or elsewhere). I'd love to be able to use makeEvent
in my own tests.