DEV Community

Cover image for Basic Integration Testing with Serverless Framework
We're Serverless! for Serverless Inc.

Posted on • Originally published at serverless.com

Basic Integration Testing with Serverless Framework

Originally posted at Serverless on July 10th, 2019

With the latest Serverless Framework release, we made it easier to test APIs built with the Serverless Framework.

Testing is important! We do it all the time when getting started developing a new service with the Serverless Framework. We might not have unit tests or a CI/CD in place yet, but at a minimum we will run serverless invoke or curl a few times with various inputs to make sure our APIs don't return 500s. After hitting [up] & [enter] in the terminal once too many times we begin to wonder if there is a better way.

Yes, you should probably write some unit tests. When you are ready for that, here is an in depth guide on writing unit tests for Node.js Serverless projects with Jest. Once you have the coverage and maturity you need, you’ll also need some integration tests. However, integration tests can be complicated and time consuming to implement. So if you need some basic integration tests in the meantime but you are not ready to commit to writing integration tests, then let me introduce you to a new testing tool in Serverless Framework to add to your testing arsenal.

Serverless Framework provides a new way to define basic integration tests for functions with HTTP endpoints. It’s goal is to enable you to test your serverless applications without having to manually write a lot of code to do so. Tests are defined in a new file, serverless.test.yml and they are tested using the serverless test command. The testing documentation goes into detail about writing tests but here is a quick preview.

As an example let’s look at this handler.js and serverless.yml file.

handler.js


This function will return hello, if a name was provided in the JSON request body, and hello, world if the name wasn't set.

Here is the serverless.yml for this function with an HTTP POST endpoint.

serverless.yml


Go ahead and deploy the service using sls deploy. Now let's write some basic integration tests in a new serverless.test.yml file.

serverless.test.yml


Once the service is deployed run sls test and you can expect output like this:

As you can see, this light-weight test framework enables us to write some basic integration tests and run them on the live service. The docs show you how to send HTTP headers, JSON bodies, string bodies, and submit forms. You can also test the responses for HTTP response codes, string bodies, or JSON content.

Originally published at https://www.serverless.com.

Top comments (0)