Skip to content

A simple way to build your JavaScript tests data

When writing Unit Tests, you will need to create test data objects for sure. Usually, those objects have tiny differences between different test cases.

There's a pattern that I especially like when I'm doing this is C#. The Builder Pattern.

The builder pattern is an elegant solution to the problem and I really like it. But, is it a simple solution for JavaScript?

Let's see how it would look like using the builder pattern in JS:

Builder pattern

As you can see, there's a lot of code needed to implement it.

How can we do it more simply?

The basic idea is to use the Spread Operator to customize a default object.

Let's see how:

Spread Operator