DEV Community

Azad Shukor
Azad Shukor

Posted on

The Mechanics Of Decision Of Test Double: Dummy

The most basic concept in test doubles is the dummy.

When testing a function, there are usually two kinds of input:

  1. Meaningful input

    Data that affects the result of the function.

  2. Dummy input

    Data that is required by the function, but does not affect the behavior we are testing.

Below is an example of meaningful data vs dummy data.

This is a calculateShipping function:

function calculateShipping(
  weight: number,
  user: { id: string },
  logger: { info: (message: string) => void }
) {
  return weight * 5;
}
Enter fullscreen mode Exit fullscreen mode

In this function, only weight affects the result.

The user and logger parameters are required, but they do not affect the shipping calculation.

const meaningfulWeight = 10;
const dummyUser = { id: "dummy-user" };
const dummyLogger = { info: () => {} };

const result = calculateShipping(
  meaningfulWeight,
  dummyUser,
  dummyLogger
);

expect(result).toBe(50);
Enter fullscreen mode Exit fullscreen mode

In this test:

const meaningfulWeight = 10;
Enter fullscreen mode Exit fullscreen mode

is meaningful input because changing it changes the result.

For example:

calculateShipping(10, dummyUser, dummyLogger); // 50
calculateShipping(20, dummyUser, dummyLogger); // 100
Enter fullscreen mode Exit fullscreen mode

But these two values are dummy inputs:

const dummyUser = { id: "dummy-user" };
const dummyLogger = { info: () => {} };
Enter fullscreen mode Exit fullscreen mode

They are only passed because calculateShipping() requires them.

Changing them does not change the result:

calculateShipping(10, { id: "user-1" }, dummyLogger); // 50
calculateShipping(10, { id: "user-2" }, dummyLogger); // 50
Enter fullscreen mode Exit fullscreen mode

So the purpose of a dummy is simple:

A dummy lets the function run without distracting the test from the behavior we actually care about.

In this case, we care about the shipping formula:

weight * 5
Enter fullscreen mode Exit fullscreen mode

We do not care about the user or logger.

That is why user and logger can be dummy values.

A dummy is useful because it keeps the test focused. Without naming something as dummy, future readers may wonder whether user or logger matters to the test.

By naming them dummyUser and dummyLogger, we are saying clearly:

This value is only here because the function requires it. It is not part of the behavior being tested.

Top comments (0)