I have recently started moving this site to AWS (Evolving Architecture: Publishing a Jekyll site to AWS using GitHub Actions and AWS CDK) and then fixed a CloudFront routing issue with a CloudFront Function (Evolving Architecture [short]: Fixing a Cloudfront Distribution with a Function). But what I didn’t do was unit test the function. (Frankly I lifted it wholesale and made use of it… 🤷.)

For reasons I decided that I wanted to write and test the Function as a TypeScript Function. And actually most of it was easy. I’m unsure how - but I found @types/aws-cloudfront-function, and after some minor local problems I had the tests working. However I couldn’t get past the problem of the generated javascript not being compatible. The basic issue is described in this StackOverflow question. Looking at the CloudFront Function docs you can see that out of the box they support ES5, but it’s a quite specific implementation.

While trying to find out how to write CloudFront Functions in TypeScript one of the articles I came across was Fabio K.’s How to unit test Cloudfront functions. So I decided to switch tack and leave the function as Javascript, and simply test that.

One minor issue I found is that the suggested .babelrc is incorrect. Based on the docs on npm I actually put this in .babelrc:

    "plugins": ["rewire"],

With tests in place all that was needed was to extend the github action to build and what is effectively a new project:

      - name: install CloudFront Function dependencies and build 🧪🔨
        run: cd js-function && npm install && npm run test

All of the details can be found in pr #5.