Article thumbnail

Unit tests review

4m
frontend
testing
quality

Intro

Understanding the basics of unit testing with generic functions as an example. Let's write several tests and learn unit tests!

Prelude

Let's try to use theory in practice. I'm assuming that you have already a project with testing environment configured.

Your first unit tests

I'm 100% sure that you've used in your career map function. Let's try to write our implementation and later we'll add unit tests.

If you're curious about performance of map, reduce and other abstractions you can check our article in which we compared them.

Take a look at following implementation of map:

Loading

Usage looks a little bit different than in Array prototype but mechanism is the same. Now we can add our unit tests. We'll use conventions from this lesson. Let's try to imagine what we want to verify - same situation like in our restaurant metaphor.

Loading

Let's add the implementation for tests.

Loading

Congrats! You know the basics!

Different convention

I think it's bad when developers using implementation details or refers to an API in test names.

Loading

Why I think it's bad?

  • Work is doubled in every rename attempt
  • The focus is on implementation - not on the purpose of something
  • Test descriptions are not clear
  • Typos risk

You can improve that by removing references to the implementation and to the API shape. It will reduce amount of time to maintain code and will make tests like documentation.

Loading

Sometimes you need to embed implementation details or API reference in descriptions. You will know when it happens. If you have problems with creating description that's 99% the case where it's better to point to implementation details.

Remember - I'm not saying it's best practice. I'm using this approach and I pointed out arguments why. Try it and create your own opinion.

Summary

That was quick! Now we know how to test simple generic functions. Sadly, testing is much more complex. We need to dive into details in next lessons. So stay with us!

If you enjoyed it, be sure to visit us on Linkedin where we regularly upload content from programming.

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.

Comments

Add your honest opinion about this article and help us improve the content.

created: 10-04-2023
updated: 10-05-2023