Learning to write good tests (TDD)

What are some good resources, tips and best practices for effective Test-Driven-Development (preferably, relating to React Js)?

I wanna get better with this as I realize how essential it is to being a great developer.

I would say that it starts with knowing how to write good tests. You’re looking at React - have you learned jest? There are others, but this works well with React.

As to TDD, I think it can get a little overblown. I do think it’s a good idea when you’re writing helper functions for example. If I’m writing a function that sorts an array (for a simple example), I will often write out a bunch of test cases, trying to think of possible edge cases, and see that they fail. Then I flesh out my function until I get those test cases to pass.

There are times when I think TDD can be tedious. For example if I’m writing out a React presentational component, I don’t see the point of writing out snapshot test beforehand. I suppose it would make more sense if I were writing tests making specific assertions (“should have two buttons with these properties”) but I don’t like getting that in depth because those can change several times while you’re developing in an agile environment.


One thing I will add…

I think unit testing is a great way to improve your coding. When they instituted testing requirements at work, it was a shock at first, but it also changed the way I code. Now I am more aware of trying to write small pure functions and breaking things into logical chunks, functions that do one thing. When writing “tests after dev”, I still am thinking about “how will I test this” and that makes me a better coder.

Here is a thread with some links.

I’m in the boat of “testing is a good thing”, and TDD forces you to build code that is testable. However, in most of the optimal scenarios when testing React ends up with code that is akin to:

  • If passed these args, my template looks like X
  • If passed these args, my template looks like Y
    etc etc.

Most of the time your tests just end up more or less checking the component as-is, any changes made to the component require changes to the test. This ends up becoming really redundant, and not adding much value to the overall project.
In these sorts of situations TDD doesn’t add much, and taking a more “higher-level” approach ends up being better. More integration tests or even e2e tests end up testing the same things, but at a higher level, and at a lower cost.

TDD ends up being more worth it for more complex situations, either in React directly, or in helper functions, or elsewhere that is easily testable.

TDD is a great practice, but they wont add value everywhere you place it equally. Focus on testing core functionality, and business logic. Don’t test just for the sake of testing unless you can afford it. Test coverage is just a number.