REMINDER
Testen and debugging Node.js in API function
-
What is the best way to test and debug Node.js in an API function? I now create a test.html page that calls the api function and throw in a few console.log()'s in the code ... but there has to be an better/easier way ... I hope
-
I enjoy writing code locally in VS code. You can use a debugger to step through the code and see what's happening 'in between lines'.
Then, when it's ready, you can put it in an AppDrag function.
However.... because the Node functions are lambda functions, they are called by an external service (a handler).
What I do is I have a file called "testFunction.js" like this:
//import your handler file or main file of Lambda const request = require("request-promise-native"); const envVars = { APIKEY : "your-appdrag-api-key", APPID : "your-appdrag-app-id" } Object.assign(process.env, envVars); let fn = require(`./${process.env.file}`); console.log("Starting up... " + process.env.file) process.on('beforeExit', (code) => { console.log('Process beforeExit event with code: ', code); }); process.on('exit', (code) => { console.log('Process exit event with code: ', code); }); //Call your exports function with required params //In AWS lambda these are event, content, and callback //event and content are JSON object and callback is a function //In my example i'm using empty JSON fn.handler({ "POST": { "somevar" : "Goes here", }, "HEADERS": {ip: "0.0.0.0", "User-Agent": "LOCAL TESTING"} }, //event function(data, ss) { //callback function with two arguments console.log(data); console.log(ss); });
Then I copy/paste the code from my AppDrag function (or use the cli tool to download it) and save it locally, for example as myfunction.js
Lastly, from the command line, (you need to have a similar version of node installed), you can run:
file="myfunction.js" node testFunction.js
That passes 'myfunction.js' to your testFunction.js as a parameter, and it calls it as if it were being called as a lambda invocation.
I'm definitely no lambda expert, and some of my terminology may be a little fishy, but that's how I test most of my code 'offline'.
-
@Daniel-Mulroy thanks for the info. I'm just getting to know JavaScript and understand a bit of how Node.js is working, but haven't got the time to look at VS Code (yet). But when I do, I'll revert back to your instructions Thanks!
-
To write and test your lambda locally you can also use Lambda Local (https://www.npmjs.com/package/lambda-local)
This would allow you to write different tests with different parameters.
Could be called through Mocha (https://www.npmjs.com/package/mocha
) testsThe whole embeded in an npm deploy script that would test it and if all tests go well call the publish API function from AppDrag CLI (https://www.npmjs.com/package/appdrag)