dougmoscrop / serverless-http

Use your existing middleware framework (e.g. Express, Koa) in AWS Lambda 🎉
Other
1.72k stars 166 forks source link

How to test the lambda handler locally #110

Closed daniakabani closed 5 years ago

daniakabani commented 5 years ago

i am trying to run a test to the handler directly from a JavaScript test file, but i get no response in return, i tried to copy the exact same event and context i got from postman request, which works fine, however on a local test file it does not work for me at all, any ideas?

dougmoscrop commented 5 years ago

A Lambda Handler is just a function, as of 2.0.0 this is an async function, so you should just have to

const serverless = require('serverless-http');
const app = ...

const handler = serverless(app);
const event = { } // api gateway event
const context = {} // sufficiently faked context

/* in your test function, like it() or whatever
  const result = await myHandler(event, context)
*/

If this doesn't work, can you list what frameworks etc you are using? If you are using a fairly big app, try removing middlewares just to see if it's one of them, and if it is, we can add tests here to guard against regression once we figure out why it's unhappy

daniakabani commented 5 years ago

Thank you for your response, i am very new to Lambda and serverless architectures, so perhaps i am doing something wrong, so bare with me, i will show you what i did, and let me know if i missed something i am pretty much following the same steps that you mentioned above

const serverless = require('serverless-http');
const app = require('path-to-app').app;
const handler = serverless(app);
const event = {
    object taken from postman
};
const context = {
    stuff taken from postman
};

describe('handlers test', () => {
    it('should do something', async () => {
        await handler(event, context);
    });
});

i am using serverless offline plugin as well, i should probably mention that i am not so sure what to pass within the event object, so what i did was using the postman event that i logged and context, and passing them through the handler function above, however i get no result at all, i guess it is because i am just passing an object or a json string to the handler so i get no actual result, is there a way to actually trigger the api gateway request locally to invoke the lambda function, or maybe my whole idea of serverlss is wrong, let me know your thoughts.

thank you!

daniakabani commented 5 years ago

somehow it is working now thank you!