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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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()

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay