The online home of John Pollard

Local Testing of an Alexa Lambda function

How I setup some simple unit tests for my Alexa Lambda function, so I could refactor it with confidence without breaking my skill

After watching last week’s fascinating Google I/O Conference, I’ve been thinking about porting my Yeltzland Alexa Skill to Google Assistant.

The Alexa Skill runs as an AWS Lambda function, and as it was my first attempt at writing a skill the code wasn’t particularly well designed for reuse.

Therefore I thought it was a good idea to find out how to:

  1. Run AWS Lambda code locally
  2. Write some unit tests against the code to check it’s running correctly
  3. Refactor the code to extract the reuseable business logic into a separate module, ready for reuse (using the unit tests to check I haven’t introduced any regressions)

Running AWS Lambda code locally

There are some great tools from Bespoken that make it pretty easy to run your AWS Lambda code locally.

The steps are as follows:

  1. Install npm install bespoken-tools -g
  2. Start the proxy server by running bst proxy lambda index.js where index.js is your Lambda code module

This sets up the Lambda function listening on http://localhost:10000 for requests.

Writing unit tests against the Lambda code to check it’s running correctly

Firstly, I wrote a simple test harness that would build some JSON in the same format as an Alexa request, which then POSTs to the proxy server setup as above and checks the response.

My skill uses dynamic data (my football team’s fixtures and results) that changes over time, so for my unit tests I just wanted to check the first part of the response - generally the non-dynamic part.

This was sufficient for my refactoring efforts, and I didn’t want to go to the effort of mocking the data requests part of my code right now.

I then wrote some simple Mocha unit tests to call each of my skills intents, and verify the response was basically as expected.

Refactoring the code

By adding the following sections to my package.json file, it makes it easy to simply run npm test to run all of the unit tests:

"devDependencies": {
    "bst": "0.0.1",
    "mocha": "^5.1.1"
  },
  "scripts": {
    "test": "mocha"
  }

I then moved all of by business logic to a separate yeltzland-speech module, and checked the tests still passed after each change, and I’m pretty confident I didn’t introduce any problems even though the code logic has been significantly refactored.

The code

If you are interested in the code described here, it’s all at GitHub at https://github.com/bravelocation/yeltzland-alexa/