Unit Tests in Serverless

So we have some simple business logic that figures out exactly how much to charge our user based on the number of notes they want to store. We want to make sure that we test all the possible cases for this before we start charging people. To do this we are going to configure unit tests for our Serverless Framework project. However, if you are looking for other strategies to test your Serverless applications, we talk about them in detail here.

We are going to use Jest for this and it is already a part of our starter project.

However, if you are starting a new Serverless Framework project. Add Jest to your dev dependencies by running the following.

$ npm install --save-dev jest @types/jest ts-jest

And update the scripts block in your package.json with the following:

"scripts": {
"test": "jest"
},

This will allow you to run your tests using the command npm test.

Then add a jest config file setting up ts-jest under ./jest.config.js:

module.exports = {
preset: 'ts-jest'
}

Alternatively, if you are using the serverless-bundle plugin to package your functions, it comes with a built-in script to transpile your code and run your tests. Add the following to your package.json instead.

"scripts": {
"test": "serverless-bundle test"
},

Add Unit Tests

Now create a new file in `tests/billing.test.ts` and add the following.
import { calculateCost } from "../libs/billing-lib";
test("Lowest tier", () => {
const storage = 10;
const cost = 4000;
const expectedCost = calculateCost(storage);
expect(cost).toEqual(expectedCost);
});
test("Middle tier", () => {
const storage = 100;
const cost = 20000;
const expectedCost = calculateCost(storage);
expect(cost).toEqual(expectedCost);
});
test("Highest tier", () => {
const storage = 101;
const cost = 10100;
const expectedCost = calculateCost(storage);
expect(cost).toEqual(expectedCost);
});

This should be straightforward. We are adding 3 tests. They are testing the different tiers of our pricing structure. We test the case where a user is trying to store 10, 100, and 101 notes. And comparing the calculated cost to the one we are expecting. You can read more about using Jest in the Jest docs here.

You might have noticed a handler.test.js file in the tests/ directory. This was a part of our starter that we can now remove.

Remove Unused Files

Remove the starter files by running the following.
$ rm handler.js
$ rm tests/handler.test.js

Run tests

And we can run our tests by using the following command in the root of our project.

$ npm test

You should see something like this:

PASS tests/billing.test.js
✓ Lowest tier (4ms)
✓ Middle tier
✓ Highest tier (1ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 1.665s
Ran all test suites.

And that's it! We have unit tests all configured.

Now we are almost ready to deploy our backend.