03 Sep 2020 - Melanie Dworak
In the process of building our Artificial Intelligence program, we the developers at Foyer Inc. knew that we had to find a streamlined and efficient way of testing our software and its individual units of source code. However, unit testing around databases gets complicated fast.
To separate from production, the easy solution is to spin up a local database and populate it as a test environment. For a smaller project, that should work well enough. But as soon as you try to scale that strategy, the cracks begin to show.
How do you parallelize tests that all hit the same database? How do you control what will be in the database to run our tests on? You could spin up a new database for each test file, but that will slow down testing and is a nightmare to implement. You could also just run your tests in series… if you’re okay with the serious slowdown in test time that it comes with.
The other problem with using a test-specific database, regardless of project size, is that your tests still won’t be unit tests. A unit test should never be hitting a database of any kind! In unit testing, you should only be interested in the logic of your code. Is the right object being passed in? Are your validators catching the malformed request? You should be able to verify without the database.
By mocking the database’s responses!
In the rest of this article series, I’ll walk you through what I and the other developers here at Foyer do to accomplish database-less unit testing on our platform.
This series comes in two separate parts. The first will discuss mocking Hapi.js’s HTTP request/response payloads; the second, implementation methods of Foyer’s Sequelize Mock v5. Feel free to only read what you need — these parts are designed to be used independently of each other!