Applications wishing to test a serverless function locally
have one of the following options:
1.
Invoke Serverless Application Model (SAM) from
the AWS public cloud command line interfaces and the steps are:
a.
sam build -t template.yml
b.
sam local invoke
The command to build the libraries for a
default index.js lambda function handler comes with the option to create a
container image. This can be very useful for portability and the image can be
executed on any container framework.
While this is optional, the local
invocation might require that all the source code and its dependencies be
transpiled into a format that is easy to interpret and run.
Enter Babel, a well-known transpiler for
this purpose and it is almost easy to invoke different formats of javascripts
and typescript notations.
2.
Another option to test the lambda function
handlers has been to write different unit tests and integration tests. These
tests can be run with Jest – a test framework that makes it easy to execute the
tests by discovering it from the build folder. All test files are usually named
as .test.js or .spec.js and the test cases follow the describe/it readable
specifications that have made unit-tests a pleasure to read and execute.
Jest is local to the node_modules folder
where all the dependencies of the lambda function handler are installed. It can
be installed with –save-dev option that eliminates the need to install it for
production builds.
Executing the jest requires a mock library
for unit tests and by virtue of the Javascript’s support for object’s prototype,
features can be inherited and substituted.
3.
A final option is to use a middleware that
exercises just the handler methods of the lambda function handler, so that they
can be invoked across the wire by curl commands. Enter Koa – a lightweight
middleware that is not bundled with anything else, and writing an http server
becomes as simple as:
const Koa = require('koa');
const app = new Koa();
// response
app.use(ctx => {
ctx.body = 'Hello Koa';
});
app.listen(3000);
and curl http://localhost:3000/
will return ‘Hello Koa’
This comes with the nice benefit
that each of the handler method can now be tried individually, and the results
will be similar to how the lambda functions are invoked.
Another way to exercise the methods
would be to include the routes:
var koa = require('koa');
var http = require('http');
var router = require('koa-router')();
var bodyParser = require('koa-body')();
router.post('/resource', bodyParser, function *(next){
console.log(this.request.body);
this.status = 200;
this.body = 'some output for post
requests';
yield(next);
});
startServerOne();
function startServerOne() {
var app = koa();
app.use(router.routes());
http.createServer(app.callback()).listen(8081);
console.log('Server at Port 8081');
}
These are some of the ways to test
lambda function handlers.
No comments:
Post a Comment