Test Your Might with Unit Testing!

Image: unsplash.comNobody loves them, but everyone has to write them. Changes are safe if there are any of them. It’s better to write them before, but it’s not too late to write them after. They are always not enough, no matter how hard one tries.All a…


This content originally appeared on Bits and Pieces - Medium and was authored by Rufat Khaslarov

Image: unsplash.com

Nobody loves them, but everyone has to write them. Changes are safe if there are any of them. It’s better to write them before, but it’s not too late to write them after. They are always not enough, no matter how hard one tries.

All aforementioned riddles are about the same thing. Just try to guess…

And that’s absolutely right, they’re about “Unit Testing”.

In the article, we’ll go through the unit testing terminology, advantages, best practices and examples. Expand on AAA pattern, FIRST principles and TDD. Let’s get started!

Definition

Unit testing is the first barrier before evil bugs and unexpected behavior of your application. It’s the cheapest and fastest tests in the testing pyramid.

“Unit testing is a type of software testing where individual units of a software are tested.”

Meet Mr. Unit!

Just to begin with, I’d like to introduce a “unit” in unit testing.

“A unit is the smallest piece of code, that can be logically separated and isolated from an application effortlessly.”

Depending on the level of abstraction, a unit might be a whole module, but most of the time it’s just a procedure or a function. Let’s create a unit for the future testing examples, in our case it’ll the getAllLongestStrings function with following requirements:

  • The function should return an array containing all longest strings of a given array;
  • The function should return an empty array in case if a given array is empty;
  • The function should return an empty array if a given value is null or undefined;

We’ve introduced the unit, so let’s start testing. And for that, I’m going to use Mocha test framework and Chai as the assertion library.

Wait a moment…

But how to write unit tests? What are the main parts of them? Well, that’s where AAA pattern comes in.

Arrange, Act and Assert (AAA) Pattern

It means that a unit test should be divided into three separate parts: arrange, act and assert.

Arrange. It’s a section where you need to prepare code required for a specific test. Initialization of objects, values of data that will be passed to the function under a test or even setting up mocks might be a part of the section.

Act. Here a tested function should be invoked with arranged parameters.

Assert. And finally, verification of result and confirmation that a function works as expected or not.

Now getting back to our function, let’s write our first unit test using new knowledge.

But the test is failing now since our function is empty, and here we’re moving on to our next section.

Test-driven development (TDD)

TDD is software development approach which implies on the writing test cases with expected behavior before writing an actual code. In simple terms, tests (in our cases, unit tests) are written for each part of an application and if they failed, a developer starts fixing code immediately.

I’d like to touch upon those steps, which seem to be of key importance for a better understanding of the TDD.

  1. Just write a single unit test checking certain scenario of the function;
  2. Run the test, which should fail because the function doesn’t have the required code;
  3. Then write “just enough” code to pass the test successfully and refactor the function;
  4. Repeat aforementioned steps over and over again.

Just a piece of cake, right?

And the name for it is a red-green refactoring. So, let’s make our code pass the test.

Congratulations! You’ve breezed through your first unit test!

As the next step, we need to write one more test for invalidating the code.

And update the code for passing it:

As you can see TDD is an iterative process, it takes more time and in most of the cases, developers simply ignores the approach and selectively write unit tests after implementation — Test Last Development (TLD).

But from my experience, with TDD developers are considering entire functionality of a unit, all edge cases and requirements better and deeper than if they’d write tests after. Therefore, I suggest applying TDD because from a long-term perspective it brings more value for your application (code quality, modularity, flexibility) and even business, than any time costs.

Advantages of Unit Testing

There’re a lot of articles explaining the benefits of unit testing from various points of view and I’m not sure that I should go through them again. Just want to emphasize the most significant ones.

First off, it helps to catch bugs earlier with minimal effort. As I mentioned before, it’s the first barrier, the first bastion for keeping your application code stable.

Secondly, refactoring is safer if unit tests are on the spot. Just change the code and run them. Unit tests like a gate keeper who knows all faces and if you’re a stranger you’ll not pass it.

And one more, it’s a real-life documentation. A newcomer can just open the tests file and read them over, he’ll understand everything related to the module right away.

But all the advantages are purged if a unit test is written in the wrong way. And here F.I.R.S.T. principles lend a hand.

F.I.R.S.T. principles

Fast. The execution of unit tests should be fast, otherwise, nobody will run them at all. Keep in mind that your teammates might have “weaker” PC than yours.

Isolated. Merely means that a unit test should not depend on one another. It must be possible to move them to another file or execute them randomly.

Repeatable. Unit tests must be executed on any environment without any issues. In other words, you should be confident that your tests will result the same on different operating systems, servers and so on.

Self-Validating. The result of test should be clear for everyone without necessity of reading logs or debugging it manually.

Timely. Tests should be written in time. There’s no need to wait for the shooting star, because it might never come.

Conclusion

Flawless victory! Thanks for reading it all!

We learned a lot of new terms, approaches and other spells. Hope it was useful for you!

If you’re interested in a final version of the function and tests, please feel free to use the link below.

Unlock 10x development with independent components

Building monolithic apps means all your code is internal and is not useful anywhere else. It just serves this one project. And as you scale to more code and people, development becomes slow and painful as everyone works in one codebase and on the same version.

But what if you build independent components first, and then use them to build any number of projects? You could accelerate and scale modern development 10x.

OSS Tools like Bit offer a powerful developer experience for building independent components and composing modular applications. Many teams start by building their Design Systems or Micro Frontends, through independent components. Give it a try →

An independent product component: watch the auto-generated dependency graph

Learn more


Test Your Might with Unit Testing! was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Rufat Khaslarov


Print Share Comment Cite Upload Translate Updates
APA

Rufat Khaslarov | Sciencx (2022-02-20T16:28:25+00:00) Test Your Might with Unit Testing!. Retrieved from https://www.scien.cx/2022/02/20/test-your-might-with-unit-testing/

MLA
" » Test Your Might with Unit Testing!." Rufat Khaslarov | Sciencx - Sunday February 20, 2022, https://www.scien.cx/2022/02/20/test-your-might-with-unit-testing/
HARVARD
Rufat Khaslarov | Sciencx Sunday February 20, 2022 » Test Your Might with Unit Testing!., viewed ,<https://www.scien.cx/2022/02/20/test-your-might-with-unit-testing/>
VANCOUVER
Rufat Khaslarov | Sciencx - » Test Your Might with Unit Testing!. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/20/test-your-might-with-unit-testing/
CHICAGO
" » Test Your Might with Unit Testing!." Rufat Khaslarov | Sciencx - Accessed . https://www.scien.cx/2022/02/20/test-your-might-with-unit-testing/
IEEE
" » Test Your Might with Unit Testing!." Rufat Khaslarov | Sciencx [Online]. Available: https://www.scien.cx/2022/02/20/test-your-might-with-unit-testing/. [Accessed: ]
rf:citation
» Test Your Might with Unit Testing! | Rufat Khaslarov | Sciencx | https://www.scien.cx/2022/02/20/test-your-might-with-unit-testing/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.