Writing tests for Azure Functions

I will build upon my blogpost on using Typescript in Azure Functions and I will also update my companion repo.

Let us begin

We will use the Jest testing framework for my tests. So first we need to add the needed dependencies. We will need jest itself, ts-jest for compiling and the types for jest. We should also add a jest config to our package.json.

yarn add -D jest ts-jest @types/jest
package.json
"jest": {
"moduleFileExtensions": [ "ts", "js" ],
"transform": {
"^.+\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testMatch": [ "**/*.test.ts" ]
}

This setup will use the ts-jest preprocessor when running our tests and it will look for tests in files named <anything>.test.ts. I like to put my test files next to my actual files. Because Typescript does not play nice with CommonJS and we can not tell Azure Functions to use the default value of the import we have to do a “hack” to be able to test it. We will change our index.ts to the following:

import { httpTriggerTS } from './httpTriggerTS';
module.exports = httpTriggerTS;

Writing the test

And then we will move our logic and types to a file named httpTriggerTS.ts. As our function is a pure function and get everything passed to it we can easily mock out its dependencies. Another thing to note is that Azure Functions have a file called sample.dat that is used to test the function in their editor. I think a best practice would be to use that file in our local tests as we then can use the same data when actually testing our or function.

As we are just using the standard http trigger function that we get from the template I will not go over that code. But this is the relevant parts of the test code (with comments):

Test code with comments for one of the possible branches.

Setting up CircleCI

With the tests setup we can now easily add CircleCI and only deploy code that runs on master by following another blogpost that I created. But to add to that post we can actually ignore branches that we do not want to build by adding this to the top of our circle.yml:

branches:
ignore:
- beta
- production

Changing settings in Azure

Now we can change our continuous integration settings in our function to use our production branch instead of master.

Setup of continuous integration from the production branch.

Now we are up and running with tests that run on every push and we only deploy code that should work on our Azure Function.

Thanks for reading and I hope it is helpful.

The changes created when writing this post are added to the repo mentioned in the start.