February 10, 2021

Testing Architect with Jest

I'm building a small project with architect a lightweight framework to manage AWS Lambda, DynamoDB and few other services to make serveless web apps.

I wanted to make integration tests with DynamoDB for my project. Fortunately architect provides a sandbox library @architect/sandbox which runs a dynalite DynamoDB server under the hood. It's all in memory, cheap to start and stop and does most things DynamoDB does. It's perfect for this. However it does use the network, and you cannot have two of them running on the same port. This isn't a problem for a single process test, but it is a problem for running tests in parallel with Jest. You can ask Jest to run all your tests in a single processes one at a time with the --runInBand flag, but that is slower and not ideal.

Additionally the DynamoDB client library inside of @architect/functions needs to know which port to use to connect to the sandbox. The Easiest way to deal with this is to set an env variable called ARC_TABLES_PORT to something unique. You have to do this before the tests load and before your code is loaded. Both the client and the sandbox will use that port.

It took me a lot longer than I care to admit to prove that you can't change the port dynamically during runtime. Some of the DynamoDB client library can pick up on a change in the env var but not all of it's interfaces do. This was very confusing and not supported.

I ended up solving this with a Jest 'setupFiles' file. I named mine jest.configureDynamoPort.js and it has one line

process.env.ARC_TABLES_PORT = process.env.JEST_WORKER_ID + 5555

I chose 5555 because it wasn't in use on my system. The JEST_WORKER_ID will be a unique numeric id for each jest processes starting at 1.

It took me a long time to get to that very simple solution. I hope it can help you too.


Roborooter.com © 2024
Powered by ⚡️ and 🤖.