TDD: Factory generator with factory.ts and faker.js to ease your testing in TypeScript applications

https://xmpro.com/xmpro-joins-industrial-internet-consortium-smart-factory-machine-learning-testbed/smart-factory-ml-testbed_mini/

When writing unit testing it is alway a good practice to mock the database with test data to achieve the F.I.R.S.T principles of unit testing.

With only a few models in an application it is not too difficult to mock the necessary test data, but when your application grows it starts to become unmanageable, for example can you image mocking data for an application with over 200 models?

A way of avoiding all the tedious work of generating all data required to test a certain method or unit of your application is taking advantage of factories, which by definition are the responsible for “manufacturing” data when needed.

Making factories generator with TypeScript

While working on a TypeScript project I came across a library called factory.ts to generate model instances by interface or type definition.

Let say we have an interface with two properties and and we want to create a factory for our department interface, the only two things we need to do is call the method from the library and then return an implementation of .

So after creating the department factory you can reference the instance elsewhere on the application…

As the snippet above demonstrates every time an instance of is required, you just need to invoke the or method from department factory and an instance will be provided, you can also easily override value of the interface properties when instantiating the factories by passing the desired properties as a parameter on the method.

Faking the factories

Generating random data for factories is great when it comes to test the performance of your code with big amount of data or simple populate a list with some random objects.

Going back to our example, we can easily generate a list of departments by assigning random data to the properties of the interface. There are a ton of libraries that help creating random data.

Department factory using faker.js

Notice that and properties are generated randomly by the library called For more details about this library check out the documentation and its API which is very powerful.

Testing with factories

Once the factories are created, it is extremely easy to mock model instances to start testing our code.

The example above shows that with fewer lines of code, instances of are provided to test the method avoiding all hassle of creating the instances manually.

Conclusion

The example used in this blog was just to demonstrated the usage of creating factories, and indeed for small projects it can be a bit overwhelming but as the application grows and unit testing is taking seriously on the project, the creation of factories comes in very handy, saving a lot of time and surely making testing easier.

Software Engineer at @redhat