in Projects, Programming, Technology

Should I write unit tests for node code?

A friend (learning node development) just asked:

Hey, another developer is encouraging me to do some unit testing using a testing framework called Mocha and Chai. What are your thoughts: must do, nice to have, or good hygiene (like pushing to GitHub and production every day)? Thanks in advance for your advice!

My answer: Must do, but it’s Level 2. In other words, as soon as you’ve grasped the basics (shipped your first app or site) – you should learn to write tests.

It’s more than just good hygiene. As your code base gets more complicated, automated testing will catch bugs that hand-testing won’t catch. You don’t have to go crazy, I’d suggest just starting with tests for the parts of your code that are hard to test by hand.
 
I like mocha. Chai is a little over-complicated. You can also just use “assert.” Other npm libraries I use for code testing:
  • Istanbul (coverage)
  • Sinon
  • Nock
  • Supertest

Longer answer: Automated testing is often required to know that your code is working. Once you’ve got a good suite of tests, you can change things with confidence and quickly verify that you haven’t broken something unexpectedly. However, It won’t guarantee that your code has no bugs (after all, tests can contain bugs too). Lastly, writing tests first (AKA “test driven development”) will help you organize your code better and write better interfaces.

Write a Comment

Comment