Test Framework for AWS Lambda
npm install lambda-tdd







Testing Framework for AWS Lambda. Very useful for integration testing as you can examine how your lambda function executes for certain input and specific environment variables. Tries to model the cloud execution as closely as possible.
- Tests are defined as JSON files
- Test are dynamically evaluated using Chai
- Lambda functions are executed using Lambda-Wrapper
- Supports external request mocking using Nock
- Allows setting of environment variables on a per test granularity
- Freeze execution to specific timestamp with Timekeeper
- Mock randomly generated data, so it does not change between test runs.
- Set lambda timeout (context.getRemainingTimeInMillis())
- Set test timeout
- Specify event input
- Test success and error responses
Example project using js-gardener and lambda-tdd can be found here.
To install run
$ npm install --save-dev lambda-tdd
js
import fs from 'smart-fs';
import minimist from 'minimist';
import LambdaTdd from 'lambda-tdd';LambdaTdd({
cwd: fs.dirname(import.meta.url),
verbose: minimist(process.argv.slice(2)).verbose === true,
timeout: minimist(process.argv.slice(2)).timeout,
nockHeal: minimist(process.argv.slice(2))['nock-heal']
}).execute();
`You can pass an array of test files to the
execute() function or a regular expression pattern. By default tests are auto detected. If a pattern is passed in only matching tests are executed.The example above allows for use of a
--filter=REGEX parameter to only execute specific tests.Note: If you are running e.g.
npm t to run your tests you need to specify the filter option with quadruple dashes. Example: $ npm t -- --filter=REGEX
$3
`json
{
"handler": "geoIp",
"envVars": {
"GOOGLE_PROJECT_ID": "123456789"
},
"event": {
"ip": "173.244.44.10"
},
"nock": {
"to": {
"match": "^.?\"http://ip-api\\.(com|ca):80\".?$"
}
},
"expect(body)": {
"to.contain": "\"United States\""
},
"timestamp": 1511072994,
"success": true,
"lambdaTimeout": 5000,
"timeout": 5000
}
`More examples can be found here.
Test Runner Options
$3
Type:
string
Default: process.cwd()Directory which other defaults are relative to.
$3
Type
string
Default: lambda-testName of this test runner for debug purposes.
$3
Type
boolean
Default: falseDisplay console output while running tests. Useful for debugging.
$3
Type
integer
Default: undefinedHard overwrite test timeout for all tests.
$3
Type
boolean or string
Default: falseSet cassette healing flag for underlying node-tdd
$3
Type
boolean
Default: falseAutomatically heals test when possible.
$3
Type:
string
Default: handler.jsHandler file containing the handler functions (specified in test).
$3
Type:
string
Default: __cassettesFolder containing nock recordings.
$3
Type:
string
Default: env-vars.ymlSpecify yaml file containing environment variables. To allow overwriting of existing environment variables prefix with
^. Otherwise an exception is thrown.Environment variables set by default are
AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY since these always get set by the AWS Lambda environment.$3
Type:
string
Default: env-vars.recording.ymlSimilar to envVarYml. Environment variables declared get applied on top of envVarYml iff this is a new test recording.
Great when secrets are needed to record tests, but they should not be committed (recommendation is to git ignore this file).
$3
Type:
string
Default: Folder containing test files.
$3
Type: boolean
Default: falseRemove rawHeaders from recordings automatically when recording.
$3
Type: object
Default: {}Allows definition of custom test file modifiers for
expect and event and for cassette recordings (pipe operator).Default custom modifiers are:
toBase64, toGzip and jsonStringify$3
Type: object
Default: {}Used to define overwrite values for cassette
reqheaders.$3
Type: function
Default: ({ test, output, expect }) => {}Called for each successful test. Can be used for additional validation.
Test File Format
$3
Type:
string
RequiredThe handler inside the handler file, i.e. if
handler.js contained
`javascript
module.exports.returnEvent = (event, context, cb) => cb(null, event);
`
we would set this to returnEvent.$3
Type
object
Default: {}Contains environment variables that are set for this test. Existing environment variables can be overwritten.
$3
Type
unix
Default: UnfrozenSet unix timestamp that test executing will see. Time does not progress if this option is set.
$3
Type
string
Default: undefinedSeed used for randomly generated bytes. This mocks
crypto.randomBytes.$3
Type
boolean
Default: falseBy default every "random function" is seeded once per test run.
When set to
true every function is re-seeded for every invocation.
Will greatly reduce "randomness" when set to true.$3
Type
integer
Default: Mocha Default TimeoutSet custom timeout in ms for lambda execution. Handy e.g. when recording nock requests.
$3
Type
object
Default: undefinedEvent object that is passed to lambda handler.
Custom actions can be applied by using the pipe character, e.g.
{ "body|JSON.stringify": {...} } could be used to make input more readable. For more examples see tests.$3
Type
integer
Default: 300000Set initial lambda timeout in ms. Exposed in lambda function through
context.getRemainingTimeInMillis().
The timeout is not enforced, but progresses as expected unless timestamp option is used.$3
Type
boolean
RequiredTrue iff execution is expected to succeed, i.e. no error is passed into callback.
$3
Type
array
Default: []Handle evaluation of response or error (uses success flag). Can define target path, e.g.
expect(some.path). Can also apply function with e.g. expect(body|JSON.parse).
More details on dynamic expect handling below.$3
Type
array
Default: []Deprecated. Use "expect" instead.
Dynamic expect logic executed against the response string. More details on dynamic expect handling below.
$3
Type
array
Default: []Deprecated. Use "expect" instead.
Dynamic expect logic executed against the error string. More details on dynamic expect handling below.
$3
Type
array
Default: []Deprecated. Use "expect" instead.
Dynamic expect logic executed against the response.body string. More details on dynamic expect handling below.
$3
Type
array
Default: []Dynamic expect logic executed against the
console output. You can use warn, info, error and log to access the different log level with e.g. logs([error]). More details on dynamic expect handling below.$3
Type
array
Default: []Dynamic expect logic executed against the nock recording. More details on dynamic expect handling below.
Note that the nock recording must already exist for this check to evaluate correctly.
_Important:_ If you are running into issues with replaying a cassette file you recorded previously, try editing the cassette and stripping information that might change. Also make sure cassette files never expose secret tokens or passwords!
$3
Type: boolean
Default: ?Remove rawHeaders from recordings automatically when recording. Defaults depends on value set in runner options.
$3
Type: array
Default: []Can define the recordings that are allowed to be unmatched.
$3
Type: array
Default: []Can define the recordings that are allowed to be out of order.
Dynamic Expect Logic
Uses Chai Assertion Library syntax written as json. Lets assume we have an output array
[1, 2] we want to validate. We can write
`js
import { expect } from 'chai';expect([1, 2]).to.contain(1);
expect([1, 2]).to.contain(2);
`
as the following json
`json
[{
"to.contain()": 1
}, {
"to": {
"contain()": 2
}
}]
``Regular expression are supported if the target is a string matching a regular expression.
- Does currently not play nicely with native modules. This is because native modules can not be invalidated.
Currently nothing planned