Dalius's blog

Thursday, February 22, 2024

Frontend testing: unit testing

One struggle in front-end development I had and I assume still have is automated testing. There are many ways how to do it (unit-testing, visual testing, integration testing, e2e testing and etc) and there are various problems with it. I will write several posts sharing how I do or how I would like to do testing in my projects.

In case you need arguments, why automated testing is important:

  • You get confidence in changing your code (or if someone changes your code).

  • You communicate intention of your code to other developers or future self.

  • Testing might help getting back into flow state faster.

  • You can be confident when someone else changes something related to your code: automatic packages upgrades, writers changing content and etc.

Let’s start with simple unit-testing. Here my idea is not to teach you how to do it, but give some guidelines how to start, what is important and what I have found useful:

  1. Ideally you already have Jest or Vitest configured for you (it might be other testing frameworks as well, but those two are the most common nowadays). If you don’t have anything yet I recommend to check Vitest “Getting Started”.

  2. Understand basics of TDD.

  3. Unit-testing is really great tool to test business logic. Usually you can isolate it from all the remaining code. In the worst case you will need to add some mocks. I recommend starting with business logic as it is the best place to start IMHO.

  4. If you don’t feel you are ready to test your own code then my recommendation would be to check TDD katas, e.g. Wix Incubator TDD katas.

  5. As well check the last part in “Seven Ineffective Coding Habits of Many Programmers” by Kevlin Henney “Uncohesive Tests”. The whole presentation is a little bit outdated but the last part is worth your time.