Unit tests for ORM with fast-check
In this article, I am going to show how to use fast-check library to test simple Users
ORM. I am assuming the ORM code is ready and will be focusing on the tests. Typescript will be used.
Fast-check
Fast-check is “Property based testing framework for JavaScript (like QuickCheck) written in TypeScript”.
What we are going to test
Mapping
ORM(Object-relational mapping) enables us to work easily with non-scalar objects like Users in a context of a database. First of all, we want to verify the mapping from Javascript into SQL primitives and vice versa works.
Queries logic
We also want to verify that logic like filtering, sorting and grouping works according to requirements.
Let’s define our objects
We have User
objects which we want to store in the ORM.
Implementation of the ORM is not important. It can be typeorm or any other.
In order to use fast-check, we need to define arbitrary for our Users.
Arbitraries — they are responsible for the random but deterministic generation of values, they may also offer shrinking capabilities
Now we can generate any number of User
objects for our tests!
Testing of the mapping
Now we can verify that mapping from Javascript into SQL and vice versa works.
Testing queries logic
Let’s test that findUsersFromMars
returns only users from Mars
Testing of more complex queries
Let’s extend our ORM with selectMany
query
Now we can ensure that selectMany
works as expected for any arguments.
Further steps
I demonstrated simple tests for very simple ORM, but this approach can be extended to
- more complex queries
- more complex objects
- stored procedures
- schema migrations
Downsides
One of the biggest downsides of this approach is a need to support Arbitrary
for each type you store in the ORM. The amount of code can be comparable to the tests themself.
Happy testing!
Originally published at https://bananamorphism.com on January 22, 2021.