npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2021 – Pkg Stats / Ryan Hefner

lambda-tdd

v3.0.7

Published

Test Framework for AWS Lambda

Downloads

1,519

Readme

Test Framework for AWS Lambda

Build Status Test Coverage Dependabot Status Dependencies NPM Downloads Semantic-Release Gardener

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.

What it does

  • 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 Projects

Example project using js-gardener and lambda-tdd can be found here.

Getting Started

To install run

$ npm install --save-dev lambda-tdd

Initialize Test Runner and Execute

const minimist = require('minimist');
const LambdaTdd = require('lambda-tdd');

LambdaTdd({
  cwd: __dirname,
  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

Test File Example

{
  "handler": "geoIp",
  "env": {
    "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

cwd

Type: string Default: process.cwd()

Directory which other defaults are relative to.

name

Type string Default: lambda-test

Name of this test runner for debug purposes.

verbose

Type boolean Default: false

Display console output while running tests. Useful for debugging.

timeout

Type integer Default: undefined

Hard overwrite test timeout for all tests.

nockHeal

Type boolean or string Default: false

Set cassette healing flag for underlying node-tdd

testHeal

Type boolean Default: false

Automatically heals test when possible.

handlerFile

Type: string Default: handler.js

Handler file containing the handler functions (specified in test).

cassetteFolder

Type: string Default: __cassettes

Folder containing nock recordings.

envVarYml

Type: string Default: env.yml

Specify 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.

envVarYmlRecording

Type: string Default: env.recording.yml

Similar 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).

testFolder

Type: string Default: ``

Folder containing test files.

flush

Type: array Default: ["aws-sdk"]

List of dependencies that are required to be flushed before test run. Useful if you need to re-initialize a module that automatically picks up environment variables on initialization (e.g. aws-sdk).

The current project files are always flushed between test runs.

This can not be used for natively compiled modules.

stripHeaders

Type: boolean Default: false

Remove rawHeaders from recordings automatically when recording.

modifiers

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

Test File Format

handler

Type: string Required

The handler inside the handler file, i.e. if handler.js contained

module.exports.returnEvent = (event, context, cb) => cb(null, event);

we would set this to returnEvent.

env

Type object Default: {}

Contains environment variables that are set for this test. Existing environment variables can be overwritten.

timestamp

Type unix Default: Unfrozen

Set unix timestamp that test executing will see. Time does not progress if this option is set.

seed

Type string Default: undefined

Seed used for randomly generated bytes. This mocks crypto.randomBytes.

reseed

Type boolean Default: false

By 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.

timeout

Type integer Default: Mocha Default Timeout

Set custom timeout in ms for lambda execution. Handy e.g. when recording nock requests.

event

Type object Default: undefined

Event 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.

lambdaTimeout

Type integer Default: 300000

Set 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.

success

Type boolean Required

True iff execution is expected to succeed, i.e. no error is passed into callback.

expect, expect(...)

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.

response (DEPRECATED)

Type array Default: []

Deprecated. Use "expect" instead. Dynamic expect logic executed against the response string. More details on dynamic expect handling below.

error (DEPRECATED)

Type array Default: []

Deprecated. Use "expect" instead. Dynamic expect logic executed against the error string. More details on dynamic expect handling below.

body (DEPRECATED)

Type array Default: []

Deprecated. Use "expect" instead. Dynamic expect logic executed against the response.body string. More details on dynamic expect handling below.

logs, logs(...)

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.

nock

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!

stripHeaders

Type: boolean Default: ?

Remove rawHeaders from recordings automatically when recording. Defaults depends on value set in runner options.

allowedUnmatchedRecordings

Type: array Default: []

Can define the recordings that are allowed to be unmatched.

allowedOutOfOrderRecordings

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

const { expect } = require('chai');

expect([1, 2]).to.contain(1);
expect([1, 2]).to.contain(2);

as the following json

[{
  "to.contain()": 1
}, {
  "to": {
    "contain()": 2
  }
}]

Regular expression are supported if the target is a string matching a regular expression.

Limitations

Contribution / What's next

Currently nothing planned