DEV Community 👩‍💻👨‍💻

Guilherme Ferreira
Guilherme Ferreira

Posted on • Originally published at gsferreira.com on

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

Top comments (1)

Collapse
 
jonashdown profile image
Jon Ashdown

the 1st example using the class based builder needs to call the build method e.g.
const order = new ProductBuilder().withDate(date).build()

Hey 😍

Want to help the DEV Community feel more like a community?

Head over to the Welcome Thread and greet some new community members!

It only takes a minute of your time, and goes a long way!