• Stars
    star
    160
  • Rank 234,703 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Plugin for Serverless Framework which adds support for test-driven development using Mocha

Serverless Mocha Plugin

Build Status

A Serverless Plugin for the Serverless Framework, which adds support for test driven development using mocha

THIS PLUGIN REQUIRES SERVERLESS V1!

More familiar with Jest? Use serverless-jest-plugin.

Introduction

This plugin does the following:

  • It provides commands to create and run tests manually
  • It provides a command to create a function, which automatically also creates a test

Installation

In your service root, run:

npm install --save-dev serverless-mocha-plugin

Add the plugin to serverless.yml:

plugins:
  - serverless-mocha-plugin

Usage

Creating functions

Functions (and associated tests) can be created using the command

sls create function -f functionName --handler handler

e.g.

sls create function -f myFunction --handler functions/myFunction/index.handler

creates a new function myFunction into serverless.yml with a code template for the handler in functions/myFunction/index.js and a Javascript function module.exports.handler as the entrypoint for the Lambda function. A test template is also created into test/myFunction.js. Optionally tests can be created to specific folder using --path or -p switch, e.g.

sls create function -f myFunction --handler functions/myFunction/index.handler --path tests

To create an http event for the lambda, add the --httpEvent parameter, i.e.

sls create function -f myFunction --handler functions/myFunction/index.handler --httpEvent "[httpVerb] [relativePath]"

e.g.

sls create function -f myFunction --handler functions/myFunction/index.handler --httpEvent "post myResource" --httpEvent "get myResource"

Creating tests

Functions can also be added manually using the mocha-create command

sls create test -f functionName

If you want to run the tests against the real Lambda functions, you can initLiveModule() instead of getWrapper(). You can also use --live flag and then you don't need to change your tests.

  let wrapped = mochaPlugin.initLiveModule('myLambdaFunctionName');

initLiveModule() and getWrapper() are helper methods to initialize lambda-wrapper, which is used under the hood. Both methods return wrapped function, which can be invoked with .run({}) method and takes event object as an argument.

Running tests

Tests can be run directly using the "invoke test" command. This also initializes the environment variables based on your serverless.yml file and the SERVERLESS_TEST_ROOT variable that defines the root for the code to be tested. If you're running the tests locally (rather than on live Lambdas, as described below), it will also set the IS_LOCAL to 'true' to match the behavior of sls invoke local.

sls invoke test [--stage stage] [--region region] [-t timeout] [-f function1] [-f function2] [...]

To use a mocha reporter (e.g. json), use the -R switch. Reporter options can be passed with the -O switch.

If no function names are passed to "invoke test", all tests are run from the test/ directory and subdirectories.

The default timeout for tests is 6 seconds. In case you need to apply a different timeout, that can be done in the test file using using .timeout(milliseconds) with the define, after, before or it -blocks. e.g.

  it('implement tests here', () => {
    ...
  }).timeout(xxx);

To run test in specific folder use --path or -p switch.

To run tests live against the actual deployed Lambdas, use the '--live' or '-l' switch. Please note that this will work only for tests created with module version 1.4 or higher.

To run tests e.g. against built artefacts that reside in some other directory, use the '--root' or '-r' switch. e.g.

  sls webpack -o testBuild
  sls invoke test --root testBuild
  rm -rf testBuild

Using own template for a test file

The templates to use for new function Files can be determined with the custom testTemplate configuration in serverless.yml

custom:
  serverless-mocha-plugin:
    testTemplate: templates/myTest.js

Currently, there are three variables available for use in the template:

  • functionName - name of the function
  • functionPath - path to the function
  • handlerName - the name of the handler function

If you'd like to get more information on the template engine, you check documentation of the EJS project.

Using own template for function file

The templates to use for new function Files can be determined with the custom functionTemplate configuration in serverless.yml

custom:
  serverless-mocha-plugin:
    functionTemplate: templates/myFunction.js

Running commands before / after tests

The plugin can be configured to run commands before / after the tests. This is done by setting preTestCommands and postTestCommands in the plugin configuration.

For example, start serverless-offline before tests and stop it after tests using the following configuration:

custom:
  serverless-mocha-plugin:
    preTestCommands: 
      - bash startOffline.sh
    postTestCommands:
      - bash stopOffline.sh

Sample startOffline.sh:

TMPFILE=/var/tmp/offline$$.log
if [ -f .offline.pid ]; then
    echo "Found file .offline.pid. Not starting."
    exit 1
fi

serverless offline 2>1 > $TMPFILE &
PID=$!
echo $PID > .offline.pid

while ! grep "server ready" $TMPFILE
do sleep 1; done

rm $TMPFILE

Note: The example relies on the output of the serverless offline command. If the start script is not working for you, replace "server ready" with the string serverless offline prints as soon as the server is ready and listening.

Sample stopOffline.sh

kill `cat .offline.pid`
rm .offline.pid

Usage with babel register

If you use mocha with babel compiler e.g. sls invoke test --compilers js:@babel/register
Babel configuration can be determined with the custom babelOptions configuration in serverless.yml

custom:
  serverless-mocha-plugin:
    babelOptions:
      presets: [["@babel/env", { "targets": { "node": "8.10" }, "shippedProposals": true, "useBuiltIns": "usage" }]]
      plugins:
        - ["@babel/plugin-transform-runtime"]

Release History (1.x)

  • 2019/11/xx - v1.12.0 - support for node12 fix --compiler option parsing
  • 2019/07/25 - v1.11.0 - support for node10 deprecated node6
  • 2019/04/02 - v1.10.0 - add timeout parameter add babel options
  • 2018/12/15 - v1.9.1 - fix to work with serverless 1.33 and later
  • 2018/09/16 - v1.9.0 - add support for --exit option
  • 2018/04/03 - v1.8.0 - add support for Node 8
  • 2017/09/10 - v1.7.0 - ability to run scripts before / after tests
  • 2017/09/09 - v1.6.0 - also run tests from subfolders of test
  • 2017/07/11 - v1.4.1 - Add option --root for running tests on e.g. webpack build results residing in other directories, add option --httpEvent to create http events when creating functions
  • 2017/07/09 - v1.4.0 - Add --live switch, add --grep switch, verify that the test runtime matches the service runtime, upgrade lambda-wrapper (returns exceptions as errors)
  • 2016/12/21 - v1.3.2 - Fix population of environment variables
  • 2016/11/28 - v1.3.1 - Added support for environment variables in Serverless 1.2
  • 2016/11/09 - v1.2.0 - Added ability to add function / test templates
  • 2016/11/09 - v1.1.0 - Added function create command.
  • 2016/09/23 - v1.0.2 - Bugfixes, configurable test timeouts
  • 2016/08/15 - v1.0.0 - Preliminary version for Serverless 1.0

License

Copyright (c) 2017 Nordcloud, licensed for users and contributors under MIT license. https://github.com/nordcloud/serverless-mocha-plugin/blob/master/LICENSE

More Repositories

1

serverless-jest-plugin

Plugin for Serverless Framework which adds support for test-driven development using Jest
JavaScript
120
star
2

serverless-kms-secrets

๐Ÿ”‘๐Ÿ”โ˜๏ธ Serverless plugin to encrypt variables with KMS (DEPRECATED)
JavaScript
113
star
3

serverless-plugin-additional-stacks

Additional Stacks Plugin for Serverless 1.x
JavaScript
101
star
4

cognitocurl

๐Ÿฆ‰๐Ÿค–Easily sign curl calls to API Gateway with Cognito authorization token.
TypeScript
90
star
5

serverless-boilerplate

Serverless project template
JavaScript
82
star
6

pat-frontend-template

React frontend template based on Vite for Nordcloud's Platform & Tools
TypeScript
58
star
7

assume-role-arn

๐Ÿค–๐ŸŽฉassume-role-arn allows you to easily assume an AWS IAM role in your CI/CD pipelines, without worrying about external dependencies.
Go
55
star
8

azure-pipelines-templates

Templates to be reused in our Azure Pipelines projects
31
star
9

lambda-wrapper

Wrapper for running lambda modules locally during development
JavaScript
30
star
10

GNUI

๐Ÿ’… Nordcloud's design system for SaaS products.
TypeScript
30
star
11

cognito-authorizer

Build your AWS API Gateway custom authorizer lambda without the need to handle tokens by yourself. Just implement the logic...
Go
24
star
12

aws-assume-role

GitHub action to assume subsequent AWS roles
Shell
23
star
13

aws-codepipeline-cfn-provider

โ˜๏ธโœจโš™๏ธAWS Codepipeline Lambda to deploy stuff using AWS CloudFormation.
Python
23
star
14

azure-tag-manager

Azure Tag Manager, enforce tags at scale.
Go
21
star
15

codepipeline-datadog-events

Tool for monitoring AWS CodePipeline status and pushing events to Datadog, Slack and Cloudwatch.
TypeScript
20
star
16

cognito-go-auth

Simple library to sign requests using cognito Google federated authentication.
Go
17
star
17

cfn-encrypt

๐Ÿ”‘๐Ÿ”โ˜๏ธ Cloudformation custom resource that enables creation of KMS encrypted strings and SSM secure parameters
Python
13
star
18

cfn-datadog

๐Ÿ•โš™๏ธCloudformation custom resources that integrate with datadog
Python
10
star
19

mfacli

Go
9
star
20

azure-go-example

๐Ÿ––Example app in go Azure SDK
Go
8
star
21

terraform-provider-imagefactory

ImageFactory terraform provider
Go
7
star
22

aws-rds-manager

โ˜๏ธ๐Ÿ› โœจ Provides utilities for the management of RDS snapshots
Python
6
star
23

ncerrors

An error wrapping library with an ability to add arbitrary fields to errors and record stack trace.
Go
4
star
24

mca-cli

CLI to help automating MCA work
TypeScript
4
star
25

mca-monitoring

Separate library for MCA monitoring generated with MCA CLI.
TypeScript
3
star
26

serverless.fi

serverless.fi website
HTML
2
star
27

klarity-scanner-vmware-cli

Klarity self-hosted scanner for your VMware environments
Go
2
star
28

klarity-apps-examples

Klarity apps examples, free to use
1
star
29

cloudtrail-activity-events

1
star
30

serverless-tdd-plugin

serverless-mocha-plugin reborn.
JavaScript
1
star
31

nordcloud-webassembly-lambda-demo

Nordcloud WebAssembly Lambda Demo
TypeScript
1
star
32

eslint-config-pat

Shareable ESLint config for PAT projects
JavaScript
1
star
33

log-forwarder

Golang based application to consume exported Cloud Logging entries via Pub/Sub subscription and log the entries on configured, central GCP Project.
Go
1
star
34

pytanko-bot

โ‰๏ธ Pytanko bot to post questions into a graphQL api (check https://github.com/nordcloud/pytanko-ui)
Go
1
star
35

lambdas-presentation-2018

JavaScript
1
star
36

aksworkshop

1
star
37

supermaestro-manifest-example

1
star
38

azure-cloud-foundation

1
star
39

kubernetes-fast-track-program

The Kubernetes Fast-Track program is an initiative to fast-track Nordcloud engineers onto Kubernetes. This Github project provides the necessary materials and tools to practice using Docker containers and Kubernetes.
Dockerfile
1
star