Giter VIP home page Giter VIP logo

lambda-tester's Introduction

Build Status npm version

lambda-tester

Simplifies writing unit tests for AWS Lambda functions using Node.js.

Features

  • Verifies correct handler behavior
  • Mocks event types with code
  • Works asynchronously
  • Supports Promises
  • Verifies Node.js runtime version
  • AWS X-Ray support [experimental]
  • Detects resource leaks [experimental]
  • Easily integrates with test frameworks (Mocha and Jasmine)
  • Handlers can be loaded and removed after execution
  • Lightweight and won't impact performance
  • Maps the environment variable LAMBDA_TASK_ROOT to the application's root
  • Automatically loads .env files
  • Works with Node 10.x, and 12.x

Installation

Install via npm.

npm install lambda-tester --save-dev

Getting Started

Lambda handlers with support for callbacks use the typical Node.js asynchronous signature:

exports.handler = function( event, context, callback ) {

    callback( null, 'success!' );
}

The following example shows a simple case for validating that the Lambda (handler) was called successfully (i.e. callback( null, result ):

const LambdaTester = require( 'lambda-tester' );

const myHandler = require( '../index' ).handler;

describe( 'handler', function() {

	it( 'test success', async function() {

		await LambdaTester( myHandler )
			.event( { name: 'Fred' } )
			.expectResult();
	});
});

If the handler calls callback( err ), then the test will fail.

Additionally, if one wanted to test for failure, then the following code would be used:

const LambdaTester = require( 'lambda-tester' );

const myHandler = require( '../index' ).handler;

describe( 'handler', function() {

	it( 'test failure', async function() {

		await LambdaTester( myHandler )
			.event( { name: 'Unknown' } )
			.expectError();
	});
});

Note: you must either return the LambdaTester instance back to the testing framework or use the await/async keywords.

Documentation

Complete documentation can be found in our documentation page.

Projects Using lambda-tester

  • vandium - Secures and simplifies AWS Lambda handlers

Feedback

We'd love to get feedback on how you're using lambda-tester and things we could add to make this tool better. Feel free to contact us at [email protected]

Compatibility

Starting with version 4.0, lambda-tester supports node versions 10 and higher. If you require support for older versions of node, then use a previous version of lambda-tester.

License

BSD-3-Clause

lambda-tester's People

Contributors

antonbazhal avatar astrosam avatar cybersam avatar dc00p avatar debugwand avatar edbo avatar jkehres avatar marcbachmann avatar munierujp avatar richardhyatt avatar s0ykaf avatar zanzamar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lambda-tester's Issues

Failed assertion prevents 'done()' from being called

The test below never finishes and just results in the test timing out with "Ensure the done() callback is being called in this test":

'use strict';

var chai = require('chai'),
    expect = chai.expect,
    LambdaTester = require('lambda-tester');

describe("LambdaTester", function() {
    it("should return from async calls", function(done) {
        return LambdaTester(function(event, context, callback) {
            callback(null, { message: "I did nothing!" });
        })
        .event({ Records: [] })
        .expectResult(function(result) {
            expect(result.message).to.equal("I did it!");
            done();
        });
    })
});

I'm running node v4.3.2 and here's my package.json file:

{
  "name": "data-file-custodian",
  "version": "0.1.0",
  "scripts": {
    "test": "mocha"
  },
 "author": "Mark J. Miller",
 "devDependencies": {
    "chai": "^3.5.0",
    "lambda-tester": "^2.6.0",
    "mocha": "^3.0.2"
  },
  "dependencies": {
    "async": "^2.0.1",
    "aws-sdk": "^2.4.13",
    "debug": "^2.2.0",
    "lodash": "^4.14.2"
  }
}

I would expect to see the failure message immediately instead of waiting for the timeout and not getting the failure message from expect.

AWS api event source

Question: What are the best practices when testing AWS api events included in the handler logic? Proxyquire?

Support node 8.10

AWS now supports node 8.10 on lambda.

Currently this library throws the following when testing on node 8.10:

Error: node.js 7.x is not currently supported, please test with an older version.

For now it is possible to bypass this with LAMBDA_TESTER_NODE_VERSION_CHECK=false

Print additional information on promise errors

Not sure if this is the problem with lambda-tester/jest or nodejs.

I'm trying to do TDD with lambda tester and thus my code fails a lot.
However, quite often I don't see the information about what went wrong.

I just get

Promise.reject() called instead of Promise.resolve()
at processOutcome (../../node_modules/lambda-tester/lib/runner.js:57:15)
at Promise.resolve.then.then.then (../../node_modules/lambda-tester/lib/runner.js:277:26)

Is there a way to also print the error from reject?

Config driven testing

Since we are trying to solve the same problem, I thought I'd post here. I've written a config driven lambda test framework here: https://github.com/simlu/lambda-tdd

We've been using something like this for several years and it works really well. Maybe an inspiration?

Anyways, would be very happy to get some insight from you and to discuss!

Can you test lambdas that use layers?

My lambda function has this path to layers /opt/models/xxxx.js

Is there a way to map that kind of path to a different location in my repo file structure before running the tests?

No way to inject "context"

Nice work! However I would like to add custom data to "context" to, for example, inject a Cognito identity.
Would recommend to add support for
.context(data)
which will basically amend context as created by createContext with all provided attributes.

Node.js version supports for lambda and codebuild

Hi, In AWS CodeBuild there is either a node version 6.3 or a 8.11 which can be selected, and by chance this is exactly on the opposite sides of your version check. Would you be able to update it to 8.11?

Edit: I have for now disabled the version check with your environment variable LAMBDA_TESTER_NODE_VERSION_CHECK=false, not necessarily the best practice

TypeScript definitions

Really nice helper, using this in my project a lot. But should I expect TypeScript definitions anytime soon?

Error: callback called

I keep getting:

  1) handler failed invocation: p= 1231231234:
     Error: callback called
      at node_modules/lambda-tester/lib/index.js:81:29
      at index.js:8:4
      at node_modules/q/q.js:1924:17
      at flush (node_modules/q/q.js:108:17)
      at _combinedTickCallback (internal/process/next_tick.js:67:7)
      at process._tickCallback (internal/process/next_tick.js:98:9)

lambda function (example):

'use strict';

exports.handler = ( event, context, callback ) => {
    if( !event.p || !/^[0-9-+()\s]+$/.test( event.p ) ) {
        callback( null, { valid: false });
    }
    else {
        callback( null, {
            valid: ( error ) ? false: true,
            data: ( error ) ? false : { p: event.p }
        });
    }
};

test:

const expect = require( 'chai' ).expect;
const LT = require( 'lambda-tester' );
const MF = require( './index' ).handler;

describe( 'handler', () => {
    [
        '1231231234'
    ].forEach( ( number ) => {
        it( 'successful invocation: p=' + number, ( done ) => {
            LT( MF )
                .event({ p: number })
                .expectSucceed( ( result ) => {
                    console.log(result);
                    expect( result.valid ).to.be.true;
                })
                .verify( done );
        });
    });
});

"Expecting a result, but received an error" when using Promise returned from function

I am calling a function which returns a Promise, but it isn't working.

This works:

const self = {
    handler: (event, context, callback) => {
        return Promise.resolve(true).then((response) => {
             callback(null, {success:response})
        });
    }
}

module.exports = self

This doesn't

const self = {
    handler: (event, context, callback) => {
        return self.foo().then((response) => {
            callback('null', {success:response})
        })
    },
    foo: () => {
        return Promise.resolve(true)
    }
}

module.exports = self

My test:

it('Checks foo', () => {
        return lambdaTester(index.handler).event({foo: 'bar'}).expectResult((result) => {
            expect(result.success).to.equal(true)
        })
    })

Doesn't work with jasmine

Hi, I tried the examples given in the documentation as well as the sample code in https://github.com/vandium-io/using-lambda-tester and failed to get it working with jasmine. It works well with mocha. But for reasons (personal preference indeed ;)) I want to use jasmine.

I'm fairly new to unit testing with node.js . What can I do to get it working?
It seems that with


it('works', () => {
  return LambdaTester(myHandler).event({}).expectResult();
});

the handler doesn't even get called with jasmine.

async method in verifier

Is there a way to call an async function from a verifier function?

Say I have something like this:

    it("should call the login handler lambda function with a username/password as if it was in the POST body", () => {
        let testBody = {
            "username": process.env.username,
            "password": process.env.password
        };
        let testEvent = {
            "path": "/login",
            "httpMethod": "POST",
            "body": JSON.stringify(testBody)
        };
        return LambdaTester(loginHandler)
            .event(testEvent)
            .expectResult(validateGoodLogin);
    });

Where validateGoodLogin calls jwt.verify which uses a callback:

    function validateGoodLogin(result) {
        expect(result.statusCode).to.equal(200);
        should.exist(result.headers);
        should.exist(result.headers["Content-Type"]);
        should.exist(result.headers["Access-Control-Allow-Origin"]);
        expect(result.headers["Content-Type"]).to.equal("application/json");
        should.exist(result.body);
        let responseObject = JSON.parse(result.body);
        should.exist(responseObject.KeystoneResponse.token);
        jwt.verify(responseObject.KeystoneResponse.token, secret, (err, decoded) => {
.
.
.
        });
    }

How can I be sure the callback is invoked before expectResult returns?

Thanks!

Encountering issue while writing my first test case.

First of all thanks for writing this simple but really effective tool. I am a novice to javascript testing through Jasmine/Karma/Chai/Mocha etc. I am trying to test one of our very simple lambdas, however, encountering an issue while running the test.

Lambda:
`exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;

var host = request.headers.host;
if (!host) {
host = request.headers.Host;
}

if (request.uri == '/apps/secure/myapps/') {
const response = {
status: '302',
statusDescription: 'Found',
httpVersion: request.httpVersion,
headers: {
Location: ['/apps/myapps/'],
},
};
callback(null, response);
} else {
callback(null, request);
}
};`

Test:
`const expect = require( 'chai' ).expect;
const LambdaTester = require( 'lambda-tester' );
const proxyquire = require( 'proxyquire' ).noCallThru();
const sinon = require( 'sinon' );
const response = {
status: '302',
statusDescription: 'Found',
httpVersion: 'v1',
header: {
Location: ['/apps/myapps/'],
},
}
describe( 'index', function() {

let lambda;

let AWSStub;

let snsStub;

beforeEach(function(){

    snsStub = {

        publish: sinon.stub()
    };

    AWSStub = {

        SNS: sinon.stub().returns( snsStub )
    };

    lambda = proxyquire( '../index',{

        'aws-sdk': AWSStub
    });
});

describe( '.handler', function(){

    let expectedUri = '/apps/secure/myapps/';

    it('success', function(){

        return LambdaTester(lambda.handler)
            .event( { uri : expectedUri })
            .expctedResult((result) => {

                expect(result).to.be.true;

            });
    });

});

});`

When I try to run the test through mocha it gives me below error
` index
.handler
1) success

0 passing (13ms)
1 failing

  1. index
    .handler
    success:
    TypeError: LambdaTester(...).event(...).expctedResult is not a function
    at Context. (test/index.test.js:79:18)`

Any help to resolve this issue and help to improve my test will be highly appreciated.

Using alternate test .env

Wonder if folks have recommendations for best way to bring in additional/alternate environmental variables. It's common to have a separate set of configs for running tests, but lambda-tester seems to only load .env.

Background: We use node-lambda to run and deploy our lambdas, which recommends placing env vars that one wants deployed in deploy.env. For example, we keep an encrypted db connection string in that file. In order to test our app's ability to decrypt that variable and connect to our db, we're currently manually loading deploy.env or test.deploy.env. This seems like it must be a common need, so I wonder if there's a more formal method of loading alternate (i.e. test) configs.

One way lambda-tester could formally support this would be to allow reading from an alternate env file path here:
https://github.com/vandium-io/lambda-tester/blob/master/lib/index.js#L526

Thanks!

Is it possible to use async/await?

I had a quick look at the code and I'm assuming it's not possible in its current state since the verifier is passed in to the expectResult method. Is that right?

Doubt about tests

Hey guys, first of all, congratulations for your project, it's awesome.

I have this function:

exports.handler = function(event, context, callback) {
  const processor = require('./src/processor');

  return processor(event)
    .then( function(res) {
      callback(null, res);
    } );
};

processor is a promise, but I don't know how to mock it response to run my unit test. It's giving me a Timeout everitime it runs. Can you guys help me with this?

Thanks a lot.

enhancement: ensure specific Node.js version

During the development of my first few lambdas using the lambda-tester I found eventually, that I used some syntactic constructs that exist in Node.js 7 but not in 4.
Since AWS supports 4.3 as most recent version at the moment, it would be helpful if lambda-tester would provide a functionality to ensure a specific Node.js major version.

As for now I will add a jasmine helper to my specs but it would be convenient to have this built into lambda-tester so that I don't have to copy it to my several lambda repositories.

Support for Promises in handler

AWS Lambda supports returning a promise now not just calling the callback. Do you plan to support this with this library. Currently I get this error

      Error: Promise.resolve() called instead of callback()
      at processOutcome (node_modules/lambda-tester/lib/runner.js:57:15)
      at Promise.resolve.then.then.then (node_modules/lambda-tester/lib/runner.js:277:26)
      at <anonymous>

Compatibility issue: [email protected] requires node>=12.13

Hey,

Since lambda-tester claims to support node 10.x and 12.x, it should not take a dependency on [email protected] as this requires node >= 12.13: https://github.com/vandium-io/lambda-event-mock/blob/901aadcd6fcfd51649408dfe008b1ccfebf178fe/package.json#L20

This actually breaks installs done using yarn on a node platform at 10.x because of the engine incompatibility issue.

Alternatively, you might want to stop advertising support for node 10.x on the 4.x branch.

Regards,
Romain.

Not able to run test on node version 9.4.0

I am having node version 9.4.0. And I am using lamda-tester of version 3.5.0

According to documentation, version 3.5.0 is supported for node version >=8.10.0.

On running the tests with above environments I get this error
Error: Please test with node.js versions: 8.10.0 - 8.999.0

Remove Node version expectation

I understand that your goal is to match the version of node that is running on AWS but for people using transpilers (TypeScript, Babel, etc.), it'd be great to be able to run our tests in both our non-transpiled and our transpiled code. This is not currently possible because of the "node.js x.y is not currently supported, please test with an older version" message.

Currently, what we are forced to do is:

  • Have one set of tests that run against most our code in the non-transpiled version. Most of our code does not need to be run in Lambda tester and can be tested without it.
  • Run all the tests transpiled + an extra set of tests that only run in the transpiled version and that uses Lambda Tester to test the actual Lambdas themselves.

Could you remove that restriction? Potentially, make it a parameter where the default is the current behavior and developers can decide if they want to remove the restriction.

Feature Request - More Lambda Runtime Environment Variables

Hi!

Been using lambda-tester for a while an it's a great experience, so first of thanks for the tool!

Currently Lambda only implements LAMBDA_TASK_ROOT of the Runtime Environment Variables specified here => https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html. It would be great if lambda-tester could inject more (or even all) of the env variables specified in the link above.

For context my current use case is using the aws-iot-device-sdk and the sdk looks for AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the Lambda Environment.

https://github.com/aws/aws-iot-device-sdk-js#export-variables-to-system-environment,

Support for callbackWaitsForEmptyEventLoop = false

Hello,

We're running into issues with our following lambda:

module.exports.handle = (event, lambdaContext, callback) => {
  lambdaContext.callbackWaitsForEmptyEventLoop = false;
  /* lambda body */
};

We're trying to test it like so:

  it('should return a 500 response if there is an HTTP error', (done) => {
    LambdaTester(handle)
      .event(defaultEvent)
      .expectResult((result) => {
        / * validations */
      })
      .verify(done);
  });

But we're getting the following error:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

I saw in this issue that using callbackWaitsForEmptyEventLoop = false is no supported, but we have use case for it (we have a constant that polls a configuration every 10 seconds so the user invocation does not have to wait for that) and would like to see if there's another way we can run the test. Is there some option for us to use lambda-tester with this code?

Thanks in advance!

lambda-tester has deprecated dependencies

looks like the lambda-tester has dependencies from the deprecated packages:

npm WARN deprecated @extra-number/[email protected]: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
npm WARN deprecated [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.

list of dependencies:
npm ls @extra-number/significant-digits

└─┬ [email protected]
└─┬ [email protected]
└── @extra-number/[email protected]

npm ls uuid

├─┬ [email protected]
│ ├─┬ [email protected]
│ │ └── [email protected]
│ └── [email protected]
└── [email protected]

Stacktrace for FailError w/ Jest

Hi,

I was wondering if you would be open to the idea of adding a console.error at lib/runner.js:82 or formatting the expecting result but error was thrown to be more descriptive.

I'm using Jest and when the lambda function is failing due to something being undefined - there is no useful stacktrace presented:

yarn test v0.23.2
$ jest 
 FAIL  test/lambda/index.spec.js
  ● lambda › it returns s3 params

    expecting result but error was thrown
      
      at FailError (node_modules/lambda-tester/lib/runner.js:25:9)
      at process._tickCallback (internal/process/next_tick.js:109:7)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.862s, estimated 1s
Ran all test suites.
error Command failed with exit code 1.

If we add a console.error, it would look more look like:

yarn test v0.23.2
$ jest 
 FAIL  test/lambda/index.spec.js
  ● Console

    console.error node_modules/lambda-tester/lib/runner.js:82
      TypeError: Cannot read property 'match' of undefined
          at getFullVersion (/jest-lambda-tester-example/src/lambda/events/release/s3.js:43:389)
          at getS3Params (/jest-lambda-tester-example/src/lambda/events/release/s3.js:49:21)
          at _callee$ (/jest-lambda-tester-example/src/lambda/index.js:9:45)
          at tryCatch (/jest-lambda-tester-example/node_modules/regenerator-runtime/runtime.js:65:40)
          at GeneratorFunctionPrototype.invoke [as _invoke] (/jest-lambda-tester-example/node_modules/regenerator-runtime/runtime.js:303:22)
          at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/jest-lambda-tester-example/node_modules/regenerator-runtime/runtime.js:117:21)
          at step (/jest-lambda-tester-example/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
          at /jest-lambda-tester-example/node_modules/babel-runtime/helpers/asyncToGenerator.js:35:14
          at Promise.F (/jest-lambda-tester-example/node_modules/core-js/library/modules/_export.js:35:28)
          at /jest-lambda-tester-example/node_modules/babel-runtime/helpers/asyncToGenerator.js:14:12
          at /jest-lambda-tester-example/src/lambda/index.js:13:123
          at Array.map (native)
          at /jest-lambda-tester-example/src/lambda/index.js:7:38
          at /jest-lambda-tester-example/node_modules/apex.js/index.js:6:15
          at error (/jest-lambda-tester-example/node_modules/lambda-tester/lib/runner.js:150:25)
          at Promise.resolve.then (/jest-lambda-tester-example/node_modules/lambda-tester/lib/runner.js:137:24)
          at process._tickCallback (internal/process/next_tick.js:109:7)

  ● lambda › it returns s3 params

    expecting result but error was thrown
      
      at FailError (node_modules/lambda-tester/lib/runner.js:25:9)
      at process._tickCallback (internal/process/next_tick.js:109:7)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.867s, estimated 1s
Ran all test suites.
error Command failed with exit code 1.

Here's a repo to demonstrate the current behavior: https://github.com/mikechau/jest-lambda-tester-example.

Support verification of responses and errors from Node 8 async handlers using return/throw

When implementing a lambda in JavaScript with Node 8, the handler can be implemented as an async function. One can then simply return a response (which is passed back to the client when doing RequestResponse-type invocation) or use throw to return an error (see https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-mode-exceptions.html).

lambda-tester currently supports verification of responses and errors when they were returned by calling callback(error, response), but not when a return or throw was used. It would be nice to have support for this, too.

fake environment variables?

hello,

i have environment variables defined in my lambda. the lambda only works if they are available, but if i use lambda-tester as is, there are no environment variables defined :/

how can i define environment variables for lambda-tester?

test execution continues even after lambda callback is called.

my lambda handler function-

exports.handler = async function(event, context, callback) {
    context.callbackWaitsForEmptyEventLoop = false;
    var headers = event.headers;
    var xOdmBusinessUnit = headers["x-odm-business-unit"];

    if (xOdmBusinessUnit == null || typeof xOdmBusinessUnit == 'undefined') {
        console.log("inside if..");
        callback("header must present",null);
    }
        console.log("outside if..");
        callback(null,"success");
};

unit test function

var expect = require('chai').expect;

var LambdaTester = require('lambda-tester').noVersionCheck();
//var tokenGenerationLambda = require('../lambda/customauthorizer/TokenGeneration');
var testLambda = require('../lambda/customauthorizer/Test');

describe('TokenGenerationTest', function () {

    it('successful invocation',
        function () {
            this.timeout(15000);

            return LambdaTester(testLambda.handler)
                .event({ "headers": { "x-odm-authorization-id": "testapp1" } })
                .expectError();

        });
});

When I run it with mocha.
Result-

  TokenGenerationTest
inside if..
outside if..
    √ successful invocation


  1 passing (41ms)

You can see, it has printed both console.log statements here. If it is going in if block then callback() inside if must have got called. Ideally code execution should return from this point, but it is going further and executing 2nd console.log statement.

Out of date documention re Jasmine

Hi there,

I am maintaining some old code at my company that happens to use Vandium and Jasmine, and I am adding some tests to the code as I go about working with it.

I think the comment here:
https://github.com/vandium-io/lambda-tester/blob/master/docs/test-frameworks.md

"Jasmine does not support Promises as return types, and thus requires an additional step when verifying Lambda handlers. Tests should be set to use asynchronous operation using the done callback and also requires verify() to be used with tests."

is out of date. I am no Jasmine expert (never used it before today), but it seems like Jasmine does now support Promises as return types, if I understood your meaning correctly.

See https://jasmine.github.io/tutorials/async

Thanks for your work providing and maintaining these libraries.

Best Regards,

Xavier Taylor

Support for array length

I'm new to Lambda and this library, so maybe this is more of a question than bug report.

When I send an array as my event:

return LambdaTester(myHandler)
            .event([{foo: 'bar'}])
            .expectResult(...);

My handler receives an object like {"0":{"foo": "bar"}} instead of an array. On AWS I can call .length, but this is not present when using lambda-tester.

Thanks!

Example code not `SyntaxError: Unexpected token =`

I'm having problems using lambda-tester. I have a fresh project and the following files:

index.js

exports.handler = function( event, context, callback ) {
  callback( null, 'success!' );
}

test/index.test.js

const LambdaTester = require( 'lambda-tester' );

const myHandler = require( '../index' ).handler;

describe( 'handler', function() {

    it( 'test success', function() {

        return LambdaTester( myHandler )
            .event( { name: 'Fred' } )
            .expectResult();
    });
});

Yet I get the following error:

matthewcanty:~/workspace (master) $ mocha test
/home/ubuntu/workspace/node_modules/lambda-tester/lib/runner.js:95
    constructor( method, verifier, options = {} ) {
                                           ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/home/ubuntu/workspace/node_modules/lambda-tester/lib/index.js:3:22)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/home/ubuntu/workspace/test/readMusicdown.test.js:1:84)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at /mnt/shared/lib/node_modules/mocha/lib/mocha.js:219:27
    at Array.forEach (native)
    at Mocha.loadFiles (/mnt/shared/lib/node_modules/mocha/lib/mocha.js:216:14)
    at Mocha.run (/mnt/shared/lib/node_modules/mocha/lib/mocha.js:468:10)
    at Object.<anonymous> (/mnt/shared/lib/node_modules/mocha/bin/_mocha:403:18)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:134:18)
    at node.js:962:3

How to run the handler without expecting anything?

Hi, im trying to run the Lambda tester withour calling .expectResolve or .expectReject
I just need the event mockers, and I will make my own testing of the function. There is any way of replicating this?

await LambdaTester(handle).event(event).run()

No support for node 7.5

In my dev environment we are using the newer node 7.5 and I would really like this project to support that so I can continue to use it.

Access to 'result' in expectError() validator

Is it possible to get access to the result in the validator function passed to expectError() when a Lambda function invokes the callback with an error AND a result?

For example when I have something like this in my Lambda handler:

            if (err) {
                let errorMessage = util.format("Error verifying Authorization token:\n%s", err);
                console.error(errorMessage);

                let principalId = "unknown";
                authenticatorResponse = generatePolicy(principalId, 'Deny', event.methodArn);
                authenticatorResponse.context = {
                    "tokenExpired": (err.name === "TokenExpiredError").toString(),
                    "decodeError": errorMessage
                };
                lambdaCallback(err, authenticatorResponse);
            }

It would be useful to give the validator access to what is in the result passed to the callback.

Add support for context.getRemainingTimeInMillis()

Add support for context.getRemainingTimeInMillis() with the ability to specify the amount of time that will normally be allocated to the lambda. Default should return the delta from Lambdas default allowed time.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.