DEV Community

José Miguel Álvarez Vañó
José Miguel Álvarez Vañó

Posted on • Updated on • Originally published at jmalvarez.dev

You should not be testing implementation details

I see developers testing implementation details in the frontend very frequently. Why is this a bad idea?

In this post I'm referring to unit tests in the frontend. There are other specific cases where it can make sense to test the implementation details, check the resources at the bottom to read more about this.

It makes it harder to maintain tests

Imagine that you have the following function:

function multiply(x, y) {
  let total = 0;
  for (let i = 0; i < y; i++) {
    total = add(total, x);
  }
  return total;
}

function add(total, quantity) {
  return total + quantity;
}
Enter fullscreen mode Exit fullscreen mode

And then you have the following tests:

test("returns the correct result", () => {
  expect(multiply(5, 3)).toEqual(15);
});

test("calls the add function the correct number of times", () => {
  multiply(5, 3);
  expect(add).toHaveBeenCalledTimes(3);
});
Enter fullscreen mode Exit fullscreen mode

In the first test we are checking that the output of the method is correct. But in the second test we are testing implementation details. If someone later comes and updates our function to the following:

function multiply(x, y) {
  return x * y;
}
Enter fullscreen mode Exit fullscreen mode

The first test will still pass but the second will fail. The function is still working fine, the output is the expected one. But still, we have to go and update the tests because one of them is returning a false negative.

Because of this we cannot rely on our tests. We cannot have confidence on them to know if the refactor was correct or not.

We should be testing our code as how other users are going to use it. If we are testing a React component, we should check what the user will get. If it is a library, our tests should resemble how other apps will use it.

By testing the output of our code we improve the developer experience with the consequence of improving the code quality of our software.

It should be easy to know if, after a refactor, our code still works or not.

Resources

Oldest comments (5)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Agree with that 😁

Just pointing out that it happens in both backend and frontend, always has been a point of discussion and agnostic to the development side

Collapse
 
jmalvarez profile image
José Miguel Álvarez Vañó

Thanks for the comment @joelbonetr! It's good to know that it also applies to the backend, I was not sure about that, thanks for letting me know.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

No problem, thanks to you for sharing that interesting post! 😄

Collapse
 
decker67 profile image
decker

Called black box testing I would think.

Collapse
 
jmalvarez profile image
José Miguel Álvarez Vañó

Yes, exactly, that's the idea.